import axios from 'axios';
import type { ApiResponse, PagedResponse } from '~/shared/types/api';
import type {
  AerialData,
  AerialDetail,
  AerialItem,
  AerialListParams,
} from '../types/aerial';

/**
 * 항공영상 목록 조회
 */
export const fetchAerialList = async (params: AerialListParams) => {
  try {
    const response = await axios.get<ApiResponse<PagedResponse<AerialItem>>>('/api/imagery/aerial/list', {
      params: {
        dateRangeType: params.dateRangeType,
        strtDttm: params.strtDttm,
        endDttm: params.endDttm,
        page: params.page ?? 0,
        size: params.size ?? 20,
      },
    });

    return {
      list: response.data.data.content,
      pagination: {
        currentPage: response.data.data.number,
        pageSize: response.data.data.size,
        totalPages: response.data.data.totalPages,
        totalItems: response.data.data.totalElements,
      },
    };
  } catch (error) {
    console.error('fetchAerialList error:', error);
    throw error;
  }
};

/**
 * 항공영상 상세 요약정보 조회
 */
export const fetchAerialDetail = async (uuid: string) => {
  try {
    const response = await axios.get<ApiResponse<AerialDetail>>(`/api/imagery/aerial/detail/${uuid}`);
    return response.data.data;
  } catch (error) {
    console.error('fetchAerialDetail error:', error);
    throw error;
  }
};

/**
 * 항공영상 상세 영상 조회 (이미지 다운로드 URL 반환)
 */
export const getAerialImageUrl = (uuid: string, imageType: 'before' | 'after' = 'before') => {
  return `/api/imagery/detail/image?uuid=${uuid}&imageType=${imageType}`;
};

/**
 * 항공영상 상세 영상 조회 (Blob으로 다운로드)
 */
export const fetchAerialImage = async (uuid: string, imageType: 'before' | 'after' = 'before') => {
  try {
    const response = await axios.get('/api/imagery/detail/image', {
      params: { uuid, imageType },
      responseType: 'blob',
    });
    return response.data;
  } catch (error) {
    console.error('fetchAerialImage error:', error);
    throw error;
  }
};

/**
 * 항공영상 데이터 등록
 */
export const registerAerialData = async (data: AerialData) => {
  try {
    const response = await axios.post('/api/imagery/aerial', data);
    return response.data.data;
  } catch (error) {
    console.error('registerAerialData error:', error);
    throw error;
  }
}
