import { wingPool } from '../db/wingDb.js';

// ============================================================
// 인터페이스
// ============================================================

interface RescueOpsListItem {
  rescueOpsSn: number;
  acdntSn: number | null;
  opsCd: string;
  acdntTpCd: string | null;
  vesselNm: string | null;
  commanderNm: string | null;
  lon: number | null;
  lat: number | null;
  locDc: string | null;
  depthM: number | null;
  currentDc: string | null;
  gmM: number | null;
  listDeg: number | null;
  trimM: number | null;
  buoyancyPct: number | null;
  oilRateLpm: number | null;
  bmRatioPct: number | null;
  totalCrew: number | null;
  survivors: number | null;
  missing: number | null;
  sttsCd: string;
  regDtm: string;
  mdfcnDtm: string;
}

interface RescueOpsDetail extends RescueOpsListItem {
  hydroData: Record<string, unknown> | null;
  gmdssData: Record<string, unknown> | null;
}

interface RescueScenarioItem {
  scenarioSn: number;
  rescueOpsSn: number;
  timeStep: string;
  scenarioDtm: string | null;
  svrtCd: string | null;
  gmM: number | null;
  listDeg: number | null;
  trimM: number | null;
  buoyancyPct: number | null;
  oilRateLpm: number | null;
  bmRatioPct: number | null;
  description: string | null;
  compartments: unknown[] | null;
  assessment: unknown[] | null;
  actions: unknown[] | null;
  sortOrd: number;
  regDtm: string;
}

interface ListOpsInput {
  sttsCd?: string;
  acdntTpCd?: string;
  search?: string;
}

// ============================================================
// 구조 작전 목록 조회
// ============================================================

export async function listOps(input?: ListOpsInput): Promise<RescueOpsListItem[]> {
  const conditions: string[] = ["USE_YN = 'Y'"];
  const params: unknown[] = [];
  let idx = 1;

  if (input?.sttsCd) {
    conditions.push(`STTS_CD = $${idx++}`);
    params.push(input.sttsCd);
  }
  if (input?.acdntTpCd) {
    conditions.push(`ACDNT_TP_CD = $${idx++}`);
    params.push(input.acdntTpCd);
  }
  if (input?.search) {
    conditions.push(`VESSEL_NM ILIKE '%' || $${idx++} || '%'`);
    params.push(input.search);
  }

  const where = 'WHERE ' + conditions.join(' AND ');

  const sql = `
    SELECT
      RESCUE_OPS_SN, ACDNT_SN, OPS_CD, ACDNT_TP_CD, VESSEL_NM, COMMANDER_NM,
      LON, LAT, LOC_DC, DEPTH_M, CURRENT_DC,
      GM_M, LIST_DEG, TRIM_M, BUOYANCY_PCT, OIL_RATE_LPM, BM_RATIO_PCT,
      TOTAL_CREW, SURVIVORS, MISSING,
      STTS_CD, REG_DTM, MDFCN_DTM
    FROM wing.RESCUE_OPS
    ${where}
    ORDER BY REG_DTM DESC
  `;

  const { rows } = await wingPool.query(sql, params);

  return rows.map((r: Record<string, unknown>) => ({
    rescueOpsSn: r.rescue_ops_sn as number,
    acdntSn: (r.acdnt_sn as number) ?? null,
    opsCd: r.ops_cd as string,
    acdntTpCd: (r.acdnt_tp_cd as string) ?? null,
    vesselNm: (r.vessel_nm as string) ?? null,
    commanderNm: (r.commander_nm as string) ?? null,
    lon: r.lon != null ? parseFloat(r.lon as string) : null,
    lat: r.lat != null ? parseFloat(r.lat as string) : null,
    locDc: (r.loc_dc as string) ?? null,
    depthM: r.depth_m != null ? parseFloat(r.depth_m as string) : null,
    currentDc: (r.current_dc as string) ?? null,
    gmM: r.gm_m != null ? parseFloat(r.gm_m as string) : null,
    listDeg: r.list_deg != null ? parseFloat(r.list_deg as string) : null,
    trimM: r.trim_m != null ? parseFloat(r.trim_m as string) : null,
    buoyancyPct: r.buoyancy_pct != null ? parseFloat(r.buoyancy_pct as string) : null,
    oilRateLpm: r.oil_rate_lpm != null ? parseFloat(r.oil_rate_lpm as string) : null,
    bmRatioPct: r.bm_ratio_pct != null ? parseFloat(r.bm_ratio_pct as string) : null,
    totalCrew: (r.total_crew as number) ?? null,
    survivors: (r.survivors as number) ?? null,
    missing: (r.missing as number) ?? null,
    sttsCd: r.stts_cd as string,
    regDtm: (r.reg_dtm as Date).toISOString(),
    mdfcnDtm: (r.mdfcn_dtm as Date).toISOString(),
  }));
}

// ============================================================
// 구조 작전 단건 상세 조회
// ============================================================

export async function getOps(sn: number): Promise<RescueOpsDetail | null> {
  const sql = `
    SELECT
      RESCUE_OPS_SN, ACDNT_SN, OPS_CD, ACDNT_TP_CD, VESSEL_NM, COMMANDER_NM,
      LON, LAT, LOC_DC, DEPTH_M, CURRENT_DC,
      GM_M, LIST_DEG, TRIM_M, BUOYANCY_PCT, OIL_RATE_LPM, BM_RATIO_PCT,
      TOTAL_CREW, SURVIVORS, MISSING,
      HYDRO_DATA, GMDSS_DATA,
      STTS_CD, REG_DTM, MDFCN_DTM
    FROM wing.RESCUE_OPS
    WHERE RESCUE_OPS_SN = $1 AND USE_YN = 'Y'
  `;

  const { rows } = await wingPool.query(sql, [sn]);
  if (rows.length === 0) return null;

  const r = rows[0] as Record<string, unknown>;

  return {
    rescueOpsSn: r.rescue_ops_sn as number,
    acdntSn: (r.acdnt_sn as number) ?? null,
    opsCd: r.ops_cd as string,
    acdntTpCd: (r.acdnt_tp_cd as string) ?? null,
    vesselNm: (r.vessel_nm as string) ?? null,
    commanderNm: (r.commander_nm as string) ?? null,
    lon: r.lon != null ? parseFloat(r.lon as string) : null,
    lat: r.lat != null ? parseFloat(r.lat as string) : null,
    locDc: (r.loc_dc as string) ?? null,
    depthM: r.depth_m != null ? parseFloat(r.depth_m as string) : null,
    currentDc: (r.current_dc as string) ?? null,
    gmM: r.gm_m != null ? parseFloat(r.gm_m as string) : null,
    listDeg: r.list_deg != null ? parseFloat(r.list_deg as string) : null,
    trimM: r.trim_m != null ? parseFloat(r.trim_m as string) : null,
    buoyancyPct: r.buoyancy_pct != null ? parseFloat(r.buoyancy_pct as string) : null,
    oilRateLpm: r.oil_rate_lpm != null ? parseFloat(r.oil_rate_lpm as string) : null,
    bmRatioPct: r.bm_ratio_pct != null ? parseFloat(r.bm_ratio_pct as string) : null,
    totalCrew: (r.total_crew as number) ?? null,
    survivors: (r.survivors as number) ?? null,
    missing: (r.missing as number) ?? null,
    hydroData: (r.hydro_data as Record<string, unknown>) ?? null,
    gmdssData: (r.gmdss_data as Record<string, unknown>) ?? null,
    sttsCd: r.stts_cd as string,
    regDtm: (r.reg_dtm as Date).toISOString(),
    mdfcnDtm: (r.mdfcn_dtm as Date).toISOString(),
  };
}

// ============================================================
// 시나리오 목록 조회
// ============================================================

export async function listScenarios(rescueOpsSn: number): Promise<RescueScenarioItem[]> {
  const sql = `
    SELECT
      SCENARIO_SN, RESCUE_OPS_SN, TIME_STEP, SCENARIO_DTM, SVRT_CD,
      GM_M, LIST_DEG, TRIM_M, BUOYANCY_PCT, OIL_RATE_LPM, BM_RATIO_PCT,
      DESCRIPTION, COMPARTMENTS, ASSESSMENT, ACTIONS,
      SORT_ORD, REG_DTM
    FROM wing.RESCUE_SCENARIO
    WHERE RESCUE_OPS_SN = $1
    ORDER BY SORT_ORD ASC
  `;

  const { rows } = await wingPool.query(sql, [rescueOpsSn]);

  return rows.map((r: Record<string, unknown>) => ({
    scenarioSn: r.scenario_sn as number,
    rescueOpsSn: r.rescue_ops_sn as number,
    timeStep: r.time_step as string,
    scenarioDtm: r.scenario_dtm != null ? (r.scenario_dtm as Date).toISOString() : null,
    svrtCd: (r.svrt_cd as string) ?? null,
    gmM: r.gm_m != null ? parseFloat(r.gm_m as string) : null,
    listDeg: r.list_deg != null ? parseFloat(r.list_deg as string) : null,
    trimM: r.trim_m != null ? parseFloat(r.trim_m as string) : null,
    buoyancyPct: r.buoyancy_pct != null ? parseFloat(r.buoyancy_pct as string) : null,
    oilRateLpm: r.oil_rate_lpm != null ? parseFloat(r.oil_rate_lpm as string) : null,
    bmRatioPct: r.bm_ratio_pct != null ? parseFloat(r.bm_ratio_pct as string) : null,
    description: (r.description as string) ?? null,
    compartments: (r.compartments as unknown[]) ?? null,
    assessment: (r.assessment as unknown[]) ?? null,
    actions: (r.actions as unknown[]) ?? null,
    sortOrd: r.sort_ord as number,
    regDtm: (r.reg_dtm as Date).toISOString(),
  }));
}
