import { api } from '@common/services/api';

// ============================================================
// 타입
// ============================================================

export interface OrgListItem {
  orgSn: number;
  orgTp: string;
  jrsdNm: string;
  areaNm: string;
  orgNm: string;
  addr: string;
  tel: string;
  lat: number;
  lng: number;
  pinSize: 'hq' | 'lg' | 'md';
  vesselCnt: number;
  skimmerCnt: number;
  pumpCnt: number;
  vehicleCnt: number;
  sprayerCnt: number;
  totalAssets: number;
}

export interface EquipItem {
  category: string;
  icon: string;
  count: number;
}

export interface ContactItem {
  role: string;
  name: string;
  phone: string;
}

export interface OrgDetail extends OrgListItem {
  equipment: EquipItem[];
  contacts: ContactItem[];
}

export interface UploadLogItem {
  logSn: number;
  fileNm: string;
  uploaderNm: string;
  uploadCnt: number;
  regDtm: string;
}

// ============================================================
// AssetOrg 호환 인터페이스 (기존 컴포넌트와 호환)
// ============================================================
export interface AssetOrgCompat {
  id: number;
  type: string;
  jurisdiction: string;
  area: string;
  name: string;
  address: string;
  phone: string;
  lat: number;
  lng: number;
  pinSize: 'hq' | 'lg' | 'md';
  vessel: number;
  skimmer: number;
  pump: number;
  vehicle: number;
  sprayer: number;
  totalAssets: number;
  equipment: EquipItem[];
  contacts: ContactItem[];
}

function toCompat(
  item: OrgListItem,
  equipment: EquipItem[] = [],
  contacts: ContactItem[] = [],
): AssetOrgCompat {
  return {
    id: item.orgSn,
    type: item.orgTp,
    jurisdiction: item.jrsdNm,
    area: item.areaNm,
    name: item.orgNm,
    address: item.addr,
    phone: item.tel,
    lat: item.lat,
    lng: item.lng,
    pinSize: item.pinSize,
    vessel: item.vesselCnt,
    skimmer: item.skimmerCnt,
    pump: item.pumpCnt,
    vehicle: item.vehicleCnt,
    sprayer: item.sprayerCnt,
    totalAssets: item.totalAssets,
    equipment,
    contacts,
  };
}

// ============================================================
// API 호출
// ============================================================

export async function fetchOrganizations(): Promise<AssetOrgCompat[]> {
  const { data } = await api.get<OrgListItem[]>('/assets/orgs');
  return data.map((item) => toCompat(item));
}

export async function fetchOrganizationDetail(sn: number): Promise<AssetOrgCompat> {
  const { data } = await api.get<OrgDetail>(`/assets/orgs/${sn}`);
  return toCompat(data, data.equipment, data.contacts);
}

export async function fetchUploadLogs(limit = 20): Promise<UploadLogItem[]> {
  const { data } = await api.get<UploadLogItem[]>(`/assets/upload-logs?limit=${limit}`);
  return data;
}

// ============================================================
// 선박보험(유류오염보장계약)
// ============================================================

export interface ShipInsuranceItem {
  insSn: number;
  shipNo: string;
  shipNm: string;
  callSign: string;
  imoNo: string;
  shipTp: string;
  shipTpDetail: string;
  ownerNm: string;
  grossTon: string;
  insurerNm: string;
  liabilityYn: string;
  oilPollutionYn: string;
  fuelOilYn: string;
  wreckRemovalYn: string;
  validStart: string;
  validEnd: string;
  issueOrg: string;
}

interface InsuranceResponse {
  rows: ShipInsuranceItem[];
  total: number;
}

export async function fetchInsurance(filters?: {
  search?: string;
  shipTp?: string;
  issueOrg?: string;
  insurer?: string;
  page?: number;
  limit?: number;
}): Promise<InsuranceResponse> {
  const params = new URLSearchParams();
  if (filters?.search) params.set('search', filters.search);
  if (filters?.shipTp) params.set('shipTp', filters.shipTp);
  if (filters?.issueOrg) params.set('issueOrg', filters.issueOrg);
  if (filters?.insurer) params.set('insurer', filters.insurer);
  if (filters?.page) params.set('page', String(filters.page));
  if (filters?.limit) params.set('limit', String(filters.limit));
  const qs = params.toString();
  const { data } = await api.get<InsuranceResponse>(`/assets/insurance${qs ? '?' + qs : ''}`);
  return data;
}
