import axios from 'axios';
import type { ApiResponse } from '~/shared/types/api';
import type { ChunkUploadParams, ChunkUploadResponse, FolderListResponse, Region } from '../types/imageryRegister';

/**
 * 업로드 지역 조회 (시/도)
 */
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;
  }
};
