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

  const rows = await queryRows(
    `SELECT I.objid AS "OBJID", I.inbound_no AS "INBOUND_NO",
            TO_CHAR(I.inbound_date,'YYYY-MM-DD') AS "INBOUND_DATE",
            V.supply_name AS "VENDOR_NAME", W.wh_name AS "WH_NAME",
            I.status AS "STATUS", I.total_amount AS "TOTAL_AMOUNT",
            (SELECT COALESCE(SUM(qty_normal),0) FROM momo_inbound_items WHERE inbound_objid = I.objid) AS "QTY_NORMAL",
            (SELECT COALESCE(SUM(qty_defect),0) FROM momo_inbound_items WHERE inbound_objid = I.objid) AS "QTY_DEFECT",
            P.proc_no AS "PROC_NO"
     FROM momo_inbounds I
     LEFT JOIN supply_mng V ON I.vendor_objid = V.objid::text
     LEFT JOIN momo_warehouses W ON I.wh_objid = W.objid
     LEFT JOIN momo_procurements P ON I.proc_objid = P.objid
     WHERE ${conds.join(" AND ")}
     ORDER BY I.inbound_date DESC, I.regdate DESC LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
