import type { AisTarget } from '../model/types';
import type { ChnPrmShipPositionDto, RecentVesselPositionDto } from './dto';

const SIGNAL_BATCH_BASE = '/signal-batch';

/* ── 내부 어댑터 ── */

function adaptChnPrmShip(dto: ChnPrmShipPositionDto): AisTarget {
  return {
    mmsi: Number(dto.mmsi),
    imo: dto.imo ?? 0,
    name: dto.name ?? '',
    callsign: dto.callsign ?? '',
    vesselType: dto.vesselType ?? '',
    lat: dto.lat,
    lon: dto.lon,
    heading: dto.heading ?? 0,
    sog: dto.sog ?? 0,
    cog: dto.cog ?? 0,
    rot: 0,
    length: dto.length ?? 0,
    width: dto.width ?? 0,
    draught: dto.draught ?? 0,
    destination: dto.destination ?? '',
    eta: '',
    status: dto.status ?? '',
    messageTimestamp: dto.messageTimestamp ?? '',
    receivedDate: '',
    source: 'chnprmship',
    classType: '',
    signalKindCode: dto.signalKindCode,
    shipImagePath: dto.shipImagePath ?? null,
    shipImageCount: dto.shipImageCount ?? 0,
  };
}

function adaptRecentVessel(dto: RecentVesselPositionDto): AisTarget {
  return {
    mmsi: Number(dto.mmsi),
    imo: dto.imo ?? 0,
    name: dto.shipNm ?? '',
    callsign: '',
    vesselType: dto.shipTy ?? '',
    lat: dto.lat,
    lon: dto.lon,
    heading: 0,
    sog: dto.sog ?? 0,
    cog: dto.cog ?? 0,
    rot: 0,
    length: 0,
    width: 0,
    draught: 0,
    destination: '',
    eta: '',
    status: '',
    messageTimestamp: dto.lastUpdate ?? '',
    receivedDate: '',
    source: 'recent',
    classType: '',
    shipKindCode: dto.shipKindCode,
    nationalCode: dto.nationalCode,
    shipImagePath: dto.shipImagePath ?? null,
    shipImageCount: dto.shipImageCount ?? 0,
  };
}

/* ── 공개 API ── */

/** 허가선박 최근 위치 → AisTarget[] */
export async function fetchChnPrmShipPositions(
  params: { minutes: number },
  signal?: AbortSignal,
): Promise<AisTarget[]> {
  const u = new URL(
    `${SIGNAL_BATCH_BASE}/api/v2/vessels/chnprmship/recent-positions`,
    window.location.origin,
  );
  u.searchParams.set('minutes', String(params.minutes));

  const res = await fetch(u, { signal, headers: { accept: 'application/json' } });
  if (!res.ok) {
    const txt = await res.text().catch(() => '');
    throw new Error(`ChnPrmShip API ${res.status}: ${txt.slice(0, 200)}`);
  }
  const json: unknown = await res.json();
  const dtos: ChnPrmShipPositionDto[] = Array.isArray(json) ? json : [];
  return dtos.map(adaptChnPrmShip);
}

/** 전체 선박 최근 위치 → AisTarget[] */
export async function fetchRecentPositions(
  params: { minutes: number },
  signal?: AbortSignal,
): Promise<AisTarget[]> {
  const u = new URL(
    `${SIGNAL_BATCH_BASE}/api/v2/vessels/recent-positions`,
    window.location.origin,
  );
  u.searchParams.set('minutes', String(params.minutes));

  const res = await fetch(u, { signal, headers: { accept: 'application/json' } });
  if (!res.ok) {
    const txt = await res.text().catch(() => '');
    throw new Error(`RecentPositions API ${res.status}: ${txt.slice(0, 200)}`);
  }
  const json: unknown = await res.json();
  const dtos: RecentVesselPositionDto[] = Array.isArray(json) ? json : [];
  return dtos.map(adaptRecentVessel);
}
