/**
 * 경비함정/순찰 API 서비스 -- 실제 백엔드 연동
 */
import type { PatrolShip } from '@data/mock/patrols';

const API_BASE = import.meta.env.VITE_API_URL ?? '/api';

// ─── 서버 응답 타입 ───────────────────────────────

export interface PatrolShipApi {
  shipId: number;
  shipCode: string;
  shipName: string;
  shipClass: string;
  tonnage: number | null;
  maxSpeedKn: number | null;
  fuelCapacityL: number | null;
  basePort: string | null;
  currentStatus: string;
  currentLat: number | null;
  currentLon: number | null;
  currentZoneCode: string | null;
  fuelPct: number | null;
  crewCount: number | null;
  isActive: boolean;
}

// ─── API 호출 ─────────────────────────────────────

export async function getPatrolShips(): Promise<PatrolShipApi[]> {
  const res = await fetch(`${API_BASE}/patrol-ships`, { credentials: 'include' });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

export async function updatePatrolShipStatus(
  id: number,
  data: {
    status: string;
    lat?: number;
    lon?: number;
    zoneCode?: string;
    fuelPct?: number;
  },
): Promise<PatrolShipApi> {
  const res = await fetch(`${API_BASE}/patrol-ships/${id}/status`, {
    method: 'PATCH',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

// ─── 하위 호환 헬퍼 (기존 PatrolShip 형식 → API 응답 매핑) ──

/** PatrolShipApi → PatrolShip (레거시) 변환 */
export function toLegacyPatrolShip(s: PatrolShipApi): PatrolShip {
  return {
    id: s.shipCode,
    name: s.shipName,
    shipClass: s.shipClass,
    speed: s.maxSpeedKn ?? 0,
    status: s.currentStatus,
    lat: s.currentLat ?? 0,
    lng: s.currentLon ?? 0,
    fuel: s.fuelPct ?? 0,
    zone: s.currentZoneCode ?? undefined,
  };
}
