const SIGNAL_BATCH_BASE = '/signal-batch';

interface TrackResponse {
  vesselId: string;
  geometry: [number, number][];
  speeds: number[];
  timestamps: string[];
  pointCount: number;
  totalDistance: number;
  shipName: string;
}

// mmsi별 캐시 (TTL 5분)
const trackCache = new Map<string, { time: number; coords: [number, number][] }>();
const CACHE_TTL = 5 * 60_000;

export async function fetchVesselTrack(mmsi: string, hours: number = 6): Promise<[number, number][]> {
  const cached = trackCache.get(mmsi);
  if (cached && Date.now() - cached.time < CACHE_TTL) return cached.coords;

  const endTime = new Date().toISOString();
  const startTime = new Date(Date.now() - hours * 3600_000).toISOString();

  try {
    const res = await fetch(`${SIGNAL_BATCH_BASE}/api/v2/tracks/vessels`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', accept: 'application/json' },
      body: JSON.stringify({ startTime, endTime, vessels: [mmsi] }),
    });
    if (!res.ok) return [];
    const data: TrackResponse[] = await res.json();
    if (!data.length || !data[0].geometry?.length) return [];
    const coords = data[0].geometry;
    trackCache.set(mmsi, { time: Date.now(), coords });
    return coords;
  } catch {
    return [];
  }
}
