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 { dateFrom, dateTo, status, vendorObjid } = await req.json().catch(() => ({}));
  const conds: string[] = ["COALESCE(P.is_del,'N') != 'Y'"];
  const params: unknown[] = [];
  let i = 1;
  if (status) { conds.push(`P.status = $${i++}`); params.push(status); }
  if (vendorObjid) { conds.push(`P.vendor_objid = $${i++}`); params.push(vendorObjid); }
  if (dateFrom) { conds.push(`P.proc_date >= $${i++}::date`); params.push(dateFrom); }
  if (dateTo) { conds.push(`P.proc_date <= $${i++}::date`); params.push(dateTo); }

  const rows = await queryRows(
    `SELECT P.objid AS "OBJID", P.proc_no AS "PROC_NO",
            TO_CHAR(P.proc_date,'YYYY-MM-DD') AS "PROC_DATE",
            P.vendor_objid AS "VENDOR_OBJID", V.supply_name AS "VENDOR_NAME",
            P.status AS "STATUS", P.total_amount AS "TOTAL_AMOUNT", P.memo AS "MEMO",
            (SELECT COUNT(*) FROM momo_procurement_items WHERE proc_objid = P.objid) AS "LINE_CNT",
            COALESCE((SELECT SUM(qty)          FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "TOTAL_QTY",
            COALESCE((SELECT SUM(received_qty) FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "RECEIVED_QTY"
     FROM momo_procurements P
     LEFT JOIN supply_mng V ON P.vendor_objid = V.objid::text
     WHERE ${conds.join(" AND ")}
     ORDER BY P.proc_date DESC, P.regdate DESC LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
