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

export interface GscAccidentListItem {
  acdntMngNo: string;
  pollNm: string;
  pollDate: string | null;
  lat: number | null;
  lon: number | null;
}

const ACDNT_ASORT_CODES = [
  '055001001',
  '055001002',
  '055001003',
  '055001004',
  '055001005',
  '055001006',
  '055003001',
  '055003002',
  '055003003',
  '055003004',
  '055003005',
  '055004003',
];

export async function listGscAccidents(limit = 20): Promise<GscAccidentListItem[]> {
  const sql = `
    SELECT DISTINCT ON (a.acdnt_mng_no)
      a.acdnt_mng_no                               AS "acdntMngNo",
      a.acdnt_title                                AS "pollNm",
      to_char(a.rcept_dt, 'YYYY-MM-DD"T"HH24:MI') AS "pollDate",
      a.rcept_dt                                   AS "rceptDt",
      b.la                                         AS "lat",
      b.lo                                         AS "lon"
    FROM gsc.tgs_acdnt_info AS a
    LEFT JOIN gsc.tgs_acdnt_lc AS b
      ON a.acdnt_mng_no = b.acdnt_mng_no
    WHERE a.acdnt_asort_code = ANY($1::varchar[])
      AND a.acdnt_title IS NOT NULL
    ORDER BY a.acdnt_mng_no, b.acdnt_lc_sn ASC
  `;

  const orderedSql = `
    SELECT "acdntMngNo", "pollNm", "pollDate", "lat", "lon"
    FROM (${sql}) t
    ORDER BY t."rceptDt" DESC NULLS LAST
    LIMIT $2
  `;

  const result = await wingPool.query<{
    acdntMngNo: string;
    pollNm: string;
    pollDate: string | null;
    lat: string | null;
    lon: string | null;
  }>(orderedSql, [ACDNT_ASORT_CODES, limit]);

  return result.rows.map((row) => ({
    acdntMngNo: row.acdntMngNo,
    pollNm: row.pollNm,
    pollDate: row.pollDate,
    lat: row.lat != null ? Number(row.lat) : null,
    lon: row.lon != null ? Number(row.lon) : null,
  }));
}
