import type { ShipImageInfo } from '../model/types';

const BASE = '/signal-batch';

export async function fetchShipImagesByImo(
  imo: number,
  signal?: AbortSignal,
): Promise<ShipImageInfo[]> {
  const res = await fetch(`${BASE}/api/v2/shipimg/${imo}`, {
    signal,
    headers: { accept: 'application/json' },
  });
  if (!res.ok) return [];
  const json: unknown = await res.json();
  return Array.isArray(json) ? json : [];
}

/** 확장자가 없으면 suffix를 붙여서 정규화 */
const ensureJpg = (path: string, suffix: '_1.jpg' | '_2.jpg'): string => {
  if (/\.jpe?g$/i.test(path)) return path;
  return `${path}${suffix}`;
};

/** path → 썸네일 URL (_1.jpg) */
export const toThumbnailUrl = (path: string): string => {
  const normalized = ensureJpg(path, '_1.jpg');
  return normalized.startsWith('http') || normalized.startsWith('/') ? normalized : `/shipimg/${normalized}`;
};

/** path → 고화질 URL (_2.jpg) */
export const toHighResUrl = (path: string): string => {
  const withExt = ensureJpg(path, '_2.jpg');
  const resolved = withExt.startsWith('http') || withExt.startsWith('/') ? withExt : `/shipimg/${withExt}`;
  return resolved.replace(/_1\.jpg$/i, '_2.jpg');
};
