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

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

export async function listGscAccidents(limit = 20): Promise<GscAccidentListItem[]> {
  const sql = `
    SELECT
      ACDNT_SN                                          AS "acdntSn",
      ACDNT_CD                                          AS "acdntMngNo",
      ACDNT_NM                                          AS "pollNm",
      to_char(OCCRN_DTM, 'YYYY-MM-DD"T"HH24:MI')        AS "pollDate",
      LAT                                               AS "lat",
      LNG                                               AS "lon"
    FROM wing.ACDNT
    WHERE ACDNT_NM IS NOT NULL
    ORDER BY OCCRN_DTM DESC NULLS LAST
    LIMIT $1
  `;

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

  return result.rows.map((row) => ({
    acdntSn: row.acdntSn,
    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,
  }));
}
