import axios from 'axios';
import type { ApiResponse, PagedResponse } from '~/shared/types/api';
import type {
  AerialDetail,
  AerialItem,
  AerialListParams,
  ChunkUploadParams,
  ChunkUploadResponse,
  FolderListResponse,
  Region,
} 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 fetchRegions = async () => {
  try {
    const response = await axios.get<ApiResponse<Region[]>>('/api/imagery/regions/provinces');
    return response.data.data;
  } catch (error) {
    console.error('fetchRegions error:', error);
    throw error;
  }
};

/**
 * 업로드 폴더 조회
 */
export const fetchFolderList = async (dirPath: string) => {
  try {
    const response = await axios.post<ApiResponse<FolderListResponse>>('/api/imagery/folder-list', {
      dirPath,
    });
    return response.data.data;
  } catch (error) {
    console.error('fetchFolderList error:', error);
    throw error;
  }
};

/**
 * 대용량 파일 분할 전송 (청크 업로드)
 */
export const uploadFileChunk = async (params: ChunkUploadParams) => {
  try {
    const formData = new FormData();
    formData.append('fileName', params.fileName);
    formData.append('fileSize', String(params.fileSize));
    formData.append('chunkIndex', String(params.chunkIndex));
    formData.append('chunkTotalIndex', String(params.chunkTotalIndex));
    formData.append('chunkFile', params.chunkFile);

    const response = await axios.post<ApiResponse<ChunkUploadResponse>>(
      '/api/imagery/upload/file-chunk-upload',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      },
    );
    return response.data.data;
  } catch (error) {
    console.error('uploadFileChunk error:', error);
    throw error;
  }
};

/**
 * 업로드 완료된 파일 병합
 */
export const completeChunkUpload = async (uuid: string) => {
  try {
    const response = await axios.put<ApiResponse<ChunkUploadResponse>>(
      `/api/imagery/upload/chunk-upload-complete/${uuid}`,
    );
    return response.data.data;
  } catch (error) {
    console.error('completeChunkUpload error:', error);
    throw error;
  }
};
