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(`EXTRACT(YEAR FROM POM.regdate) = $${idx++}`);
    params.push(body.year);
  }
  if (body.partner_objid) {
    conditions.push(`POM.partner_objid = $${idx++}`);
    params.push(body.partner_objid);
  }
  if (body.part_no) {
    conditions.push(`POP.part_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.part_no);
  }
  if (body.part_name) {
    conditions.push(`POP.part_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.part_name);
  }

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

  const sql = `
    SELECT POP.objid::text AS "OBJID",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "PARTNER_NAME",
      POP.part_no AS "PART_NO",
      POP.part_name AS "PART_NAME",
      POP.spec AS "SPEC",
      POP.material AS "MATERIAL",
      POP.unit AS "UNIT_NAME",
      COALESCE(POP.partner_price, '0') AS "UNIT_PRICE",
      POM.delivery_date AS "START_DATE",
      '' AS "END_DATE",
      TO_CHAR(POM.regdate, 'YYYY-MM-DD') AS "REG_DATE",
      POP.remark AS "REMARK"
    FROM purchase_order_part POP
    JOIN purchase_order_master POM ON POM.objid = POP.purchase_order_master_objid
    WHERE ${where}
    ORDER BY POM.regdate DESC
  `;

  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
