// 매입 입금관리 목록 — 발주요청(REQUESTED) 또는 입금완료(PAID) 매입발주 노출
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, vendorObjid, status } = body as {
    dateFrom?: string; dateTo?: string; vendorObjid?: string; status?: string;
  };

  const cond: string[] = ["COALESCE(P.is_del,'N') != 'Y'", "P.status IN ('REQUESTED','PAID')"];
  const params: unknown[] = [];
  let i = 1;
  if (dateFrom)    { cond.push(`P.proc_date >= $${i++}::date`); params.push(dateFrom); }
  if (dateTo)      { cond.push(`P.proc_date <= $${i++}::date`); params.push(dateTo); }
  if (vendorObjid) { cond.push(`P.vendor_objid = $${i++}::text`); params.push(vendorObjid); }
  if (status)      { cond.push(`P.status = $${i++}`); params.push(status); }

  const rows = await queryRows(
    `SELECT
       P.objid::text                     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",
       V.charge_user_name                AS "VENDOR_CONTACT",
       P.total_amount                    AS "TOTAL_AMOUNT",
       P.status                          AS "STATUS",
       P.payment_terms                   AS "PAYMENT_TERMS",
       TO_CHAR(P.paid_date,'YYYY-MM-DD') AS "PAID_DATE",
       P.paid_amount                     AS "PAID_AMOUNT",
       P.paid_method                     AS "PAID_METHOD",
       P.paid_memo                       AS "PAID_MEMO"
     FROM momo_procurements P
     LEFT JOIN supply_mng V ON V.objid::text = P.vendor_objid
     WHERE ${cond.join(" AND ")}
     ORDER BY P.proc_date DESC, P.regdate DESC
     LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
