import { api } from '@common/services/api';
import type {
  AerialMediaItem,
  CctvCameraItem,
  SatRequestItem,
  CreateSatRequestInput,
  DroneStreamItem,
  SatellitePass,
} from '@interfaces/aerial/AerialInterface';

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

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 function getAerialMediaViewUrl(sn: number): string {
  return `/api/aerial/media/${sn}/view`;
}

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);
}

export async function uploadAerialMedia(
  file: File,
  metadata: {
    equipTpCd?: string;
    equipNm?: string;
    mediaTpCd?: string;
    acdntSn?: string;
    memo?: string;
  },
): Promise<{ aerialMediaSn: number }> {
  const form = new FormData();
  form.append('file', file);
  if (metadata.equipTpCd) form.append('equipTpCd', metadata.equipTpCd);
  if (metadata.equipNm) form.append('equipNm', metadata.equipNm);
  if (metadata.mediaTpCd) form.append('mediaTpCd', metadata.mediaTpCd);
  if (metadata.acdntSn) form.append('acdntSn', metadata.acdntSn);
  if (metadata.memo) form.append('memo', metadata.memo);
  const response = await api.post<{ aerialMediaSn: number }>('/aerial/media/upload', form, {
    headers: { 'Content-Type': undefined },
    timeout: 300_000,
  });
  return response.data;
}

/**
 * 여러 이미지 파일을 /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;
}

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