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[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(POM.regdate, 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.po_no) {
    conditions.push(`POM.purchase_order_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.po_no);
  }
  if (body.supplier_name) {
    conditions.push(`COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') LIKE '%' || $${idx++} || '%'`);
    params.push(body.supplier_name);
  }

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

  const rows = await queryRows(
    `SELECT POM.objid::text AS "OBJID",
       POM.purchase_order_no AS "PO_NO",
       POM.project_no AS "PROJECT_NO",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "SUPPLIER_NAME",
       POM.title AS "PO_NAME",
       POM.delivery_date AS "PO_DATE",
       POM.delivery_date AS "DELIVERY_DATE",
       COALESCE(POM.total_supply_price, '0') AS "PO_AMOUNT",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = POM.status LIMIT 1), POM.status) AS "STATUS_NAME",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = POM.writer LIMIT 1), POM.writer) AS "WRITER_NAME"
     FROM purchase_order_master POM
     WHERE ${where}
     ORDER BY POM.regdate DESC
`,
    params
  );

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