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

// BOM 등록된 프로젝트/유닛의 PART 목록 (common.getBomPartList 대응)
// 원본 쿼리: common.xml line 3080
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 contractObjId = String(body.contract_objid || body.OBJID || "");
  const unitCode = String(body.unit_code || body.UNIT_CODE || "");
  if (!contractObjId || !unitCode) {
    return NextResponse.json({ RESULTLIST: [] });
  }

  const rows = await queryRows(
    `SELECT
        BPQ.part_no::varchar AS "CODE",
        (SELECT part_no FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "NAME",
        (SELECT part_name FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "PART_NAME",
        (SELECT spec FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "SPEC",
        (SELECT maker FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "MAKER",
        (SELECT material FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "MATERIAL",
        (SELECT (SELECT code_name FROM comm_code CC WHERE CC.code_id = part_type) FROM part_mng O WHERE O.objid::varchar = BPQ.part_no) AS "PART_TYPE"
      FROM part_bom_report PBR, bom_part_qty BPQ
      WHERE PBR.objid = BPQ.bom_report_objid::varchar
        AND PBR.contract_objid = $1
        AND PBR.unit_code = $2
`,
    [contractObjId, unitCode],
  );
  return NextResponse.json({ RESULTLIST: rows });
}
