/**
 * 단속 이력/계획 API 서비스
 */

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

// ─── 페이지 응답 공통 타입 ────────────────────────

export interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  number: number;
  size: number;
}

// ─── 단속 기록 ────────────────────────────────────

export interface EnforcementRecord {
  id: number;
  enfUid: string;
  eventId: number | null;
  enforcedAt: string;
  zoneCode: string | null;
  areaName: string | null;
  lat: number | null;
  lon: number | null;
  vesselMmsi: string | null;
  vesselName: string | null;
  flagCountry: string | null;
  violationType: string | null;
  action: string;
  result: string | null;
  aiMatchStatus: string | null;
  aiConfidence: number | null;
  patrolShipId: number | null;
  enforcedByName: string | null;
  remarks: string | null;
  createdAt: string;
}

export interface CreateRecordRequest {
  eventId?: number;
  enforcedAt: string;
  zoneCode?: string;
  areaName?: string;
  lat?: number;
  lon?: number;
  vesselMmsi?: string;
  vesselName?: string;
  flagCountry?: string;
  violationType?: string;
  action: string;
  result?: string;
  aiMatchStatus?: string;
  aiConfidence?: number;
  patrolShipId?: number;
  remarks?: string;
}

// ─── 단속 계획 ────────────────────────────────────

export interface EnforcementPlan {
  id: number;
  planUid: string;
  title: string;
  zoneCode: string | null;
  areaName: string | null;
  lat: number | null;
  lon: number | null;
  plannedDate: string;
  riskLevel: string | null;
  riskScore: number | null;
  assignedShipCount: number;
  assignedCrew: number;
  status: string;
  alertStatus: string | null;
}

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

export async function getEnforcementRecords(params?: {
  violationType?: string;
  vesselMmsi?: string;
  page?: number;
  size?: number;
}): Promise<PageResponse<EnforcementRecord>> {
  const query = new URLSearchParams();
  if (params?.violationType) query.set('violationType', params.violationType);
  if (params?.vesselMmsi) query.set('vesselMmsi', params.vesselMmsi);
  query.set('page', String(params?.page ?? 0));
  query.set('size', String(params?.size ?? 20));
  const res = await fetch(`${API_BASE}/enforcement/records?${query}`, {
    credentials: 'include',
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

export async function createEnforcementRecord(
  data: CreateRecordRequest,
): Promise<EnforcementRecord> {
  const res = await fetch(`${API_BASE}/enforcement/records`, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

export async function getEnforcementPlans(params?: {
  status?: string;
  page?: number;
  size?: number;
}): Promise<PageResponse<EnforcementPlan>> {
  const query = new URLSearchParams();
  if (params?.status) query.set('status', params.status);
  query.set('page', String(params?.page ?? 0));
  query.set('size', String(params?.size ?? 20));
  const res = await fetch(`${API_BASE}/enforcement/plans?${query}`, {
    credentials: 'include',
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

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

/** @deprecated EnforcementRecord를 직접 사용하세요 */
export interface LegacyEnforcementRecord {
  id: string;
  date: string;
  zone: string;
  vessel: string;
  violation: string;
  action: string;
  aiMatch: string;
  result: string;
}

/** EnforcementRecord → LegacyEnforcementRecord 변환 */
export function toLegacyRecord(r: EnforcementRecord): LegacyEnforcementRecord {
  return {
    id: r.enfUid,
    date: r.enforcedAt,
    zone: r.areaName ?? r.zoneCode ?? '-',
    vessel: r.vesselName ?? r.vesselMmsi ?? '-',
    violation: r.violationType ?? '-',
    action: r.action,
    aiMatch: r.aiMatchStatus === 'MATCH' ? '일치' : '불일치',
    result: r.result ?? '-',
  };
}
