import { api } from '@common/services/api';

import type {
  IncidentListItem,
  PredExecItem,
  WeatherInfo,
  MediaInfo,
  IncidentDetail,
  IncidentCompat,
  NearbyOrgItem,
} from '@interfaces/incidents/IncidentsInterface';
import type { AerialMediaItem } from '@interfaces/aerial/AerialInterface';


function toCompat(item: IncidentListItem): IncidentCompat {
  const dt = new Date(item.occrnDtm);
  const statusMap: Record<string, 'active' | 'investigating' | 'closed'> = {
    ACTIVE: 'active',
    INVESTIGATING: 'investigating',
    CLOSED: 'closed',
  };
  return {
    id: String(item.acdntSn),
    name: item.acdntNm,
    status: statusMap[item.acdntSttsCd] ?? 'active',
    date: dt.toISOString().slice(0, 10),
    time: dt.toTimeString().slice(0, 5),
    region: item.regionNm,
    office: item.officeNm,
    location: { lat: item.lat, lon: item.lng },
    causeType: item.acdntTpCd,
    oilType: item.oilTpCd ?? undefined,
    prediction:
      item.hasPredCompleted || item.hasHnsCompleted || item.hasRescueCompleted
        ? '예측완료'
        : undefined,
    mediaCount: item.mediaCnt,
    hasImgAnalysis: item.hasImgAnalysis || undefined,
  };
}

// ============================================================
// API 호출 함수
// ============================================================

export async function fetchIncidentsRaw(): Promise<IncidentListItem[]> {
  const { data } = await api.get<IncidentListItem[]>('/incidents');
  return data;
}

export async function fetchIncidents(filters?: {
  status?: string;
  region?: string;
  search?: string;
  startDate?: string;
  endDate?: string;
}): Promise<IncidentCompat[]> {
  const params = new URLSearchParams();
  if (filters?.status) params.set('status', filters.status);
  if (filters?.region) params.set('region', filters.region);
  if (filters?.search) params.set('search', filters.search);
  if (filters?.startDate) params.set('startDate', filters.startDate);
  if (filters?.endDate) params.set('endDate', filters.endDate);

  const query = params.toString();
  const url = query ? `/incidents?${query}` : '/incidents';
  const { data } = await api.get<IncidentListItem[]>(url);
  return data.map(toCompat);
}

export async function fetchIncidentDetail(sn: number): Promise<IncidentDetail> {
  const { data } = await api.get<IncidentDetail>(`/incidents/${sn}`);
  return data;
}

export async function fetchIncidentWeather(sn: number): Promise<WeatherInfo | null> {
  try {
    const { data } = await api.get<WeatherInfo>(`/incidents/${sn}/weather`);
    return data;
  } catch {
    return null;
  }
}

export async function fetchIncidentMedia(sn: number): Promise<MediaInfo | null> {
  try {
    const { data } = await api.get<MediaInfo>(`/incidents/${sn}/media`);
    return data;
  } catch {
    return null;
  }
}

export async function fetchIncidentPredictions(sn: number): Promise<PredExecItem[]> {
  const { data } = await api.get<PredExecItem[]>(`/incidents/${sn}/predictions`);
  return data;
}

export async function fetchNearbyOrgs(
  lat: number,
  lng: number,
  radiusNm: number,
): Promise<NearbyOrgItem[]> {
  const { data } = await api.get<NearbyOrgItem[]>('/assets/orgs/nearby', {
    params: { lat, lng, radius: radiusNm },
  });
  return data;
}

// ============================================================
// 사고 관련 이미지 (AERIAL_MEDIA)
// ============================================================


export async function fetchIncidentAerialMedia(acdntSn: number): Promise<AerialMediaItem[]> {
  try {
    const { data } = await api.get<AerialMediaItem[]>('/aerial/media', {
      params: { acdntSn },
    });
    return data;
  } catch {
    return [];
  }
}

export function getMediaImageUrl(aerialMediaSn: number): string {
  return `/api/aerial/media/${aerialMediaSn}/download`;
}
