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

// 원본: salesMng.SalesBomPartListByProjectUnit — 프로젝트+유닛에 등록된 구매BOM 부품 목록
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const projectObjId = String(body.project_objid || body.project_no || "");
  const unitCode = String(body.unit_code || body.unit_name || "");
  if (!projectObjId || !unitCode) return NextResponse.json({ RESULTLIST: [] });

  const rows = await queryRows(
    `SELECT T1.parent_objid AS "BOM_REPORT_OBJID",
       T1.part_objid AS "PART_OBJID",
       T1.objid::text AS "SALES_BOM_REPORT_PART_OBJID",
       T1.supply_objid AS "SUPPLY_OBJID",
       PM.part_name AS "PART_NAME",
       PM.part_no AS "PART_NO",
       PM.spec AS "SPEC",
       PM.maker AS "MAKER",
       PM.unit AS "UNIT",
       BPQ.qty AS "ORDER_QTY"
     FROM sales_bom_report_part T1
       JOIN part_bom_report PBR ON PBR.objid = T1.parent_objid
       JOIN bom_part_qty BPQ ON BPQ.bom_report_objid = PBR.objid AND T1.part_objid = BPQ.part_no
       JOIN part_mng PM ON T1.part_objid = PM.objid::varchar
     WHERE PBR.contract_objid = $1 AND PBR.unit_code = $2
     ORDER BY BPQ.seq`,
    [projectObjId, unitCode],
  );

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