import { api } from '@common/services/api';
import type { ScatSegment, ScatDetail } from '../components/scatTypes';
import { esiColor } from '../components/scatConstants';

// ============================================================
// 백엔드 API 응답 타입
// ============================================================

export interface ApiZoneItem {
  cstSrvyZoneSn: number;
  zoneCd: string;
  zoneNm: string;
  jrsdNm: string;
  sectCnt: number;
  latCenter: number;
  lngCenter: number;
  latRange: number;
  lngRange: number;
}

export interface ApiSectionListItem {
  cstSectSn: number;
  sectCd: string;
  sectNm: string;
  cstTpCd: string;
  esiCd: string;
  esiNum: number;
  lenM: number;
  snstvtCd: string;
  srvySttsCd: string;
  lat: number;
  lng: number;
  tags: string[];
  zoneCd: string;
  zoneNm: string;
  jrsdNm: string;
}

export interface ApiSectionDetail extends ApiSectionListItem {
  geomJson: Record<string, unknown> | null;
  shoreTp: string | null;
  accessDc: string | null;
  accessPt: string | null;
  sensitiveInfo: { t: string; v: string }[];
  cleanupMethods: string[];
  endCriteria: string[];
  notes: string[];
}

// ============================================================
// 프론트 호환 변환 함수
// ============================================================

const sensFromESI = (n: number): ScatSegment['sensitivity'] =>
  n >= 9 ? '최상' : n >= 7 ? '상' : n >= 5 ? '중' : '하';

function toScatSegment(item: ApiSectionListItem): ScatSegment {
  const lengthM = Number(item.lenM) || 0;
  return {
    id: item.cstSectSn,
    code: item.sectCd,
    area: item.zoneNm,
    name: item.sectNm,
    type: item.cstTpCd,
    esi: item.esiCd,
    esiNum: item.esiNum,
    length: `${lengthM.toLocaleString()}.0 m`,
    lengthM,
    sensitivity: (item.snstvtCd as ScatSegment['sensitivity']) || sensFromESI(item.esiNum),
    status: (item.srvySttsCd as ScatSegment['status']) || '미조사',
    lat: item.lat,
    lng: item.lng,
    tags: item.tags ?? [],
    jurisdiction: item.jrsdNm,
  };
}

function toScatDetail(item: ApiSectionDetail): ScatDetail {
  const lengthM = Number(item.lenM) || 0;
  return {
    code: item.sectCd,
    name: item.sectNm,
    esi: item.esiCd,
    esiColor: esiColor(item.esiNum),
    lat: item.lat,
    lng: item.lng,
    type: item.shoreTp ?? item.cstTpCd,
    substrate: item.cstTpCd,
    length: `${lengthM.toLocaleString()}.0 m`,
    sensitivity: item.snstvtCd,
    status: item.srvySttsCd,
    access: item.accessDc ?? '',
    accessPt: item.accessPt ?? '',
    sensitive: item.sensitiveInfo ?? [],
    cleanup: item.cleanupMethods ?? [],
    endCriteria: item.endCriteria ?? [],
    notes: item.notes ?? [],
  };
}

// ============================================================
// API 호출 함수
// ============================================================

export async function fetchOffices(): Promise<string[]> {
  const { data } = await api.get<string[]>('/scat/offices');
  return data;
}

export async function fetchJurisdictions(officeCd?: string): Promise<string[]> {
  const params = officeCd ? `?officeCd=${encodeURIComponent(officeCd)}` : '';
  const { data } = await api.get<string[]>(`/scat/jurisdictions${params}`);
  return data;
}

export async function fetchZones(jurisdiction?: string, officeCd?: string): Promise<ApiZoneItem[]> {
  const params = new URLSearchParams();
  if (jurisdiction) params.set('jurisdiction', jurisdiction);
  if (officeCd) params.set('officeCd', officeCd);
  const query = params.toString();
  const url = query ? `/scat/zones?${query}` : '/scat/zones';
  const { data } = await api.get<ApiZoneItem[]>(url);
  return data;
}

export interface SectionFilters {
  zone?: string;
  status?: string;
  sensitivity?: string;
  jurisdiction?: string;
  search?: string;
  officeCd?: string;
}

export async function fetchSections(filters?: SectionFilters): Promise<ScatSegment[]> {
  const params = new URLSearchParams();
  if (filters?.zone) params.set('zone', filters.zone);
  if (filters?.status) params.set('status', filters.status);
  if (filters?.sensitivity) params.set('sensitivity', filters.sensitivity);
  if (filters?.jurisdiction) params.set('jurisdiction', filters.jurisdiction);
  if (filters?.search) params.set('search', filters.search);
  if (filters?.officeCd) params.set('officeCd', filters.officeCd);

  const query = params.toString();
  const url = query ? `/scat/sections?${query}` : '/scat/sections';
  const { data } = await api.get<ApiSectionListItem[]>(url);
  return data.map(toScatSegment);
}

export async function fetchSectionDetail(sn: number): Promise<ScatDetail> {
  const { data } = await api.get<ApiSectionDetail>(`/scat/sections/${sn}`);
  return toScatDetail(data);
}
