import { api } from '@common/services/api';
import type {
  OrgListItem,
  EquipItem,
  ContactItem,
  OrgDetail,
  UploadLogItem,
  AssetOrgCompat,
  InsuranceResponse,
} from '@interfaces/assets/AssetsInterface';

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 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;
}
