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

// ============================================================
// 항공 방제 API
// ============================================================

// === AERIAL_MEDIA ===
export interface AerialMediaItem {
  aerialMediaSn: number;
  acdntSn: number | null;
  fileNm: string;
  orgnlNm: string | null;
  filePath: string | null;
  lon: number | null;
  lat: number | null;
  locDc: string | null;
  equipTpCd: string; // drone/plane/satellite
  equipNm: string;
  mediaTpCd: string; // 사진/영상/적외선/SAR/가시광/광학
  takngDtm: string | null;
  fileSz: string | null;
  resolution: string | null;
}

// === CCTV_CAMERA ===
export interface CctvCameraItem {
  cctvSn: number;
  cameraNm: string;
  regionNm: string;
  lon: number | null;
  lat: number | null;
  locDc: string | null;
  coordDc: string | null;
  sttsCd: string; // LIVE/OFFLINE/MAINT
  ptzYn: string;
  sourceNm: string | null;
  streamUrl: string | null;
}

// === SAT_REQUEST ===
export interface SatRequestItem {
  satReqSn: number;
  reqCd: string;
  acdntSn: number | null;
  lon: number | null;
  lat: number | null;
  zoneDc: string | null;
  coordDc: string | null;
  zoneAreaKm2: number | null;
  satNm: string | null;
  providerNm: string | null;
  resolution: string | null;
  purposeDc: string | null;
  reqstrNm: string | null;
  reqDtm: string | null;
  expectedRcvDtm: string | null;
  sttsCd: string; // PENDING/SHOOTING/COMPLETED/CANCELLED
}

export interface CreateSatRequestInput {
  reqCd: string;
  acdntSn?: number;
  lon?: number;
  lat?: number;
  zoneDc?: string;
  zoneAreaKm2?: number;
  satNm?: string;
  providerNm?: string;
  resolution?: string;
  purposeDc?: string;
  reqstrNm?: string;
  expectedRcvDtm?: string;
}

export async function fetchAerialMedia(params?: {
  equipType?: string;
  mediaType?: string;
  acdntSn?: number;
  search?: string;
}): Promise<AerialMediaItem[]> {
  const response = await api.get<AerialMediaItem[]>('/aerial/media', { params });
  return response.data;
}

export async function fetchCctvCameras(params?: {
  region?: string;
  status?: string;
}): Promise<CctvCameraItem[]> {
  const response = await api.get<CctvCameraItem[]>('/aerial/cctv', { params });
  return response.data;
}

export async function fetchSatRequests(params?: { status?: string }): Promise<SatRequestItem[]> {
  const response = await api.get<SatRequestItem[]>('/aerial/sat-requests', { params });
  return response.data;
}

export async function createSatRequest(
  input: CreateSatRequestInput,
): Promise<{ satReqSn: number }> {
  const response = await api.post<{ satReqSn: number }>('/aerial/sat-requests', input);
  return response.data;
}

export async function downloadAerialMedia(sn: number, fileName: string): Promise<void> {
  const res = await api.get(`/aerial/media/${sn}/download`, { responseType: 'blob' });
  const url = URL.createObjectURL(res.data as Blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

/**
 * 여러 이미지 파일을 /aerial/stitch 엔드포인트로 전송해 합성 JPEG Blob을 반환한다.
 * FastAPI /stitch → pic_gps.py 스티칭 파이프라인 프록시.
 */
export async function stitchImages(files: File[]): Promise<Blob> {
  const form = new FormData();
  files.forEach((f) => form.append('files', f));
  const response = await api.post<Blob>('/aerial/stitch', form, {
    responseType: 'blob',
    timeout: 310_000,
    headers: { 'Content-Type': undefined }, // 기본 application/json 제거 → 브라우저가 multipart/form-data 자동 설정
  });
  return response.data;
}

// === DRONE STREAM ===
export interface DroneStreamItem {
  id: string;
  name: string;
  shipName: string;
  droneModel: string;
  ip: string;
  rtspUrl: string;
  region: string;
  status: 'idle' | 'starting' | 'streaming' | 'error';
  hlsUrl: string | null;
  error: string | null;
}

export async function fetchDroneStreams(): Promise<DroneStreamItem[]> {
  const response = await api.get<DroneStreamItem[]>('/aerial/drone/streams');
  return response.data;
}

export async function startDroneStreamApi(
  id: string,
): Promise<{ success: boolean; hlsUrl?: string; error?: string }> {
  const response = await api.post<{ success: boolean; hlsUrl?: string; error?: string }>(
    `/aerial/drone/streams/${id}/start`,
  );
  return response.data;
}

export async function stopDroneStreamApi(id: string): Promise<{ success: boolean }> {
  const response = await api.post<{ success: boolean }>(`/aerial/drone/streams/${id}/stop`);
  return response.data;
}

// ============================================================
// UP42 위성 패스 조회
// ============================================================

export interface SatellitePass {
  id: string;
  satellite: string;
  provider: string;
  type: 'optical' | 'sar' | 'elevation';
  resolution: string;
  color: string;
  startTime: string;
  endTime: string;
  maxElevation: number;
  direction: 'ascending' | 'descending';
  orbit: Array<{ lat: number; lon: number }>;
}

export async function fetchSatellitePasses(): Promise<SatellitePass[]> {
  const response = await api.get<{ passes: SatellitePass[] }>('/aerial/satellite/passes');
  return response.data.passes;
}
