import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// 자재관리 > 자금관리 (공급업체별 발주/입고 금액 집계)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const conditions: string[] = ["POM.status = 'approvalComplete'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(POM.regdate, 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.month) {
    conditions.push(`TO_CHAR(POM.regdate, 'MM') = $${idx++}`);
    params.push(body.month);
  }
  if (body.partner_objid) {
    conditions.push(`POM.partner_objid = $${idx++}`);
    params.push(body.partner_objid);
  }

  const where = conditions.join(" AND ");

  const rows = await queryRows(
    `SELECT POM.partner_objid AS "PARTNER_OBJID",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "PARTNER_NAME",
       -- 발주금액
       SUM(COALESCE(NULLIF(POM.total_supply_price,'')::numeric, 0)) AS "ORDER_AMOUNT",
       -- 입고금액 (입고된 파트의 공급가 합산)
       COALESCE(SUM((SELECT SUM(COALESCE(NULLIF(AP2.receipt_qty,'')::numeric, 0) * COALESCE(NULLIF(POP2.partner_price,'')::numeric, 0))
                     FROM purchase_order_part POP2
                     LEFT JOIN arrival_plan AP2 ON AP2.order_part_objid = POP2.objid::text
                     WHERE POP2.purchase_order_master_objid = POM.objid)), 0) AS "DELIVERY_AMOUNT",
       -- 지급 관련 (placeholder — 별도 지급 테이블 확인 필요)
       0 AS "PAYMENT_PLAN_AMOUNT",
       0 AS "PAYMENT_DONE_AMOUNT",
       SUM(COALESCE(NULLIF(POM.total_supply_price,'')::numeric, 0)) AS "UNPAID_AMOUNT",
       POM.delivery_date AS "PAYMENT_PLAN_DATE",
       '' AS "PAYMENT_STATUS_NAME",
       '' AS "REMARK"
     FROM purchase_order_master POM
     WHERE ${where}
     GROUP BY POM.partner_objid, POM.delivery_date
     ORDER BY "PARTNER_NAME"
`,
    params
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
