import { api } from '@common/services/api';
import type {
  PredictionAnalysis,
  PredictionDetail,
  BacktrackResult,
  TrajectoryResponse,
  SensitiveResourceCategory,
  SensitiveResourceFeature,
  SensitiveResourceFeatureCollection,
  SpreadParticlesGeojson,
  HydrDataStep,
  OilSpillSummaryResponse,
  ImageAnalyzeResult,
  GscAccidentListItem,
} from '@interfaces/prediction/PredictionInterface';

export type {
  PredictionAnalysis,
  PredictionDetail,
  BacktrackResult,
  TrajectoryResponse,
  SensitiveResourceCategory,
  SensitiveResourceFeature,
  SensitiveResourceFeatureCollection,
  SpreadParticlesGeojson,
  HydrDataStep,
  OilSpillSummaryResponse,
};

export const fetchPredictionAnalyses = async (params?: {
  search?: string;
  acdntSn?: number;
}): Promise<PredictionAnalysis[]> => {
  const response = await api.get<PredictionAnalysis[]>('/prediction/analyses', { params });
  return response.data;
};

export const fetchPredictionDetail = async (acdntSn: number): Promise<PredictionDetail> => {
  const response = await api.get<PredictionDetail>(`/prediction/analyses/${acdntSn}`);
  return response.data;
};

export const fetchBacktrack = async (sn: number): Promise<BacktrackResult> => {
  const response = await api.get<BacktrackResult>(`/prediction/backtrack/${sn}`);
  return response.data;
};

export const fetchBacktrackByAcdnt = async (acdntSn: number): Promise<BacktrackResult | null> => {
  const response = await api.get<BacktrackResult[]>('/prediction/backtrack', {
    params: { acdntSn },
  });
  return response.data.length > 0 ? response.data[0] : null;
};

export const createBacktrack = async (input: {
  acdntSn: number;
  lon: number;
  lat: number;
  srchRadiusNm?: number;
  anlysRange?: string;
  estSpilDtm?: string;
}): Promise<BacktrackResult> => {
  const response = await api.post<BacktrackResult>('/prediction/backtrack', input);
  return response.data;
};

// ============================================================
// 확산 예측 시뮬레이션 (OpenDrift 연동)
// ============================================================

export const fetchAnalysisTrajectory = async (
  acdntSn: number,
  predRunSn?: number,
): Promise<TrajectoryResponse> => {
  const response = await api.get<TrajectoryResponse>(
    `/prediction/analyses/${acdntSn}/trajectory`,
    predRunSn != null ? { params: { predRunSn } } : undefined,
  );
  return response.data;
};

export const fetchSensitiveResources = async (
  acdntSn: number,
): Promise<SensitiveResourceCategory[]> => {
  const response = await api.get<SensitiveResourceCategory[]>(
    `/prediction/analyses/${acdntSn}/sensitive-resources`,
  );
  return response.data;
};

export const fetchSensitiveResourcesGeojson = async (
  acdntSn: number,
): Promise<SensitiveResourceFeatureCollection> => {
  const response = await api.get<SensitiveResourceFeatureCollection>(
    `/prediction/analyses/${acdntSn}/sensitive-resources/geojson`,
  );
  return response.data;
};

export const fetchPredictionParticlesGeojson = async (
  acdntSn: number,
): Promise<SpreadParticlesGeojson> => {
  const response = await api.get<SpreadParticlesGeojson>(
    `/prediction/analyses/${acdntSn}/spread-particles`,
  );
  return response.data;
};

export const fetchSensitivityEvaluationGeojson = async (
  acdntSn: number,
): Promise<{ type: 'FeatureCollection'; features: unknown[] }> => {
  const response = await api.get<{ type: 'FeatureCollection'; features: unknown[] }>(
    `/prediction/analyses/${acdntSn}/sensitivity-evaluation`,
  );
  return response.data;
};

// ============================================================
// 이미지 업로드 분석
// ============================================================

export const analyzeImage = async (file: File, acdntNm?: string): Promise<ImageAnalyzeResult> => {
  const formData = new FormData();
  formData.append('image', file);
  if (acdntNm?.trim()) formData.append('acdntNm', acdntNm.trim());
  const response = await api.post<ImageAnalyzeResult>('/prediction/image-analyze', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 330_000,
  });
  return response.data;
};

// ============================================================
// GSC 외부 수집 사고 목록 (확산 예측 입력 셀렉트용)
// ============================================================

export const fetchGscAccidents = async (): Promise<GscAccidentListItem[]> => {
  const response = await api.get<GscAccidentListItem[]>('/gsc/accidents');
  return response.data;
};

// ============================================================
// 유류 확산 요약
// ============================================================

export const fetchOilSpillSummary = async (
  acdntSn: number,
  predRunSn?: number,
): Promise<OilSpillSummaryResponse> => {
  const response = await api.get<OilSpillSummaryResponse>(
    `/prediction/analyses/${acdntSn}/oil-summary`,
    predRunSn != null ? { params: { predRunSn } } : undefined,
  );
  return response.data;
};
