// 매입 입금관리 목록 — 입금이 의미 있는 진행상태(발주요청/입고중/입고완료) 노출.
//   진행상태(STATUS)와 결재상태(IS_PAID = paid_date 유무) 를 분리해서 내려준다.
//   payStatus 파라미터: PAID(입금완료) / UNPAID(미입금) / 전체.
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensureProcPaymentSeparation } from "@/lib/momo-proc";

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

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

  const cond: string[] = ["COALESCE(P.is_del,'N') != 'Y'", "P.status IN ('REQUESTED','PARTIAL','RECEIVED')"];
  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); }
  // 결재상태 필터 (입금완료/미입금). 하위호환: 기존 status=PAID/REQUESTED 도 결재필터로 해석.
  const pay = payStatus || (status === "PAID" ? "PAID" : status === "REQUESTED" ? "UNPAID" : "");
  if (pay === "PAID")   cond.push(`P.paid_date IS NOT NULL`);
  if (pay === "UNPAID") cond.push(`P.paid_date IS NULL`);

  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",
       -- 발주/입고/미입고 수량·금액 — 부분입고 시 실제 들어온 만큼만 입금하기 위해.
       COALESCE((SELECT SUM(qty)                                                 FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "TOTAL_QTY",
       COALESCE((SELECT SUM(COALESCE(received_qty,0))                            FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "RECEIVED_QTY",
       COALESCE((SELECT SUM(COALESCE(received_qty,0) * cost_price)               FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "RECEIVED_AMOUNT",
       COALESCE((SELECT SUM((qty - COALESCE(received_qty,0)) * cost_price)       FROM momo_procurement_items WHERE proc_objid = P.objid), 0) AS "PENDING_AMOUNT",
       P.status                          AS "STATUS",
       (P.paid_date IS NOT NULL)         AS "IS_PAID",
       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 });
}
