// 전자세금계산서 발행 이력 — 관리자 전용
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  const body = await req.json().catch(() => ({}));
  const { dateFrom, dateTo, status, customerObjid } = body as {
    dateFrom?: string; dateTo?: string; status?: string; customerObjid?: string;
  };

  const cond: string[] = ["COALESCE(E.is_del, 'N') != 'Y'"];
  const params: unknown[] = [];
  let i = 1;

  if (dateFrom)       { cond.push(`E.issue_date >= $${i++}::date`); params.push(dateFrom); }
  if (dateTo)         { cond.push(`E.issue_date <= $${i++}::date`); params.push(dateTo); }
  if (status)         { cond.push(`E.status = $${i++}`);            params.push(status); }
  if (customerObjid)  { cond.push(`E.customer_objid = $${i++}`);    params.push(customerObjid); }

  const rows = await queryRows(
    `SELECT
       E.objid              AS "OBJID",
       E.order_objid        AS "ORDER_OBJID",
       E.customer_objid     AS "CUSTOMER_OBJID",
       U.user_name          AS "BUYER_NAME",
       E.invoice_kind       AS "INVOICE_KIND",
       E.invoice_type       AS "INVOICE_TYPE",
       E.issue_method       AS "ISSUE_METHOD",
       TO_CHAR(E.issue_date, 'YYYY-MM-DD') AS "ISSUE_DATE",
       E.total_supply       AS "TOTAL_SUPPLY",
       E.total_vat          AS "TOTAL_VAT",
       E.total_amount       AS "TOTAL_AMOUNT",
       E.nts_invoice_no     AS "NTS_INVOICE_NO",
       E.nts_response_code  AS "NTS_RESPONSE_CODE",
       E.nts_response_msg   AS "NTS_RESPONSE_MSG",
       E.status             AS "STATUS",
       TO_CHAR(E.regdate, 'YYYY-MM-DD HH24:MI') AS "REGDATE"
     FROM momo_einvoices E
     LEFT JOIN user_info U ON U.user_id = E.customer_objid
     WHERE ${cond.join(" AND ")}
     ORDER BY E.issue_date DESC, E.regdate DESC
     LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
