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

// 설계수량 조회 (inventoryMng.getPartQTYInfoList 대응)
// 원본: inventoryMng.xml line 1739
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 partObjId = String(body.part_objid || body.PART_OBJID || "");
  const projectObjId = String(body.project_objid || body.PROJECT_OBJID || "");
  const unitCode = String(body.unit_code || body.UNIT_CODE || "");
  if (!partObjId || !projectObjId || !unitCode) {
    return NextResponse.json({ RESULTLIST: [] });
  }

  const rows = await queryRows(
    `SELECT
        T.*,
        (COALESCE(NULLIF(T."DESIGN_QTY1", '')::numeric, 0) * COALESCE(T."QTY1", 0)
          * COALESCE(NULLIF(T."QTY3", '')::numeric, 1)) AS "DESIGN_QTY"
      FROM (
        SELECT
          BPQ.bom_report_objid AS "BOM_REPORT_OBJID",
          BPQ.qty AS "DESIGN_QTY1",
          (SELECT MAX(COALESCE(NULLIF(BPQ.qty, '')::numeric, 0))
             FROM bom_part_qty BPQ
             WHERE BPQ.bom_report_objid = PBR.objid AND COALESCE(BPQ.parent_part_no, '') = '') AS "QTY1",
          (SELECT SUM(COALESCE(NULLIF(BPQ3.qty, '')::numeric, 0))::text
             FROM bom_part_qty BPQ3
             WHERE BPQ3.bom_report_objid = PBR.objid AND BPQ3.child_objid = BPQ.parent_objid) AS "QTY3",
          PM.objid AS "PART_OBJID",
          PM.part_no AS "PART_NO",
          PM.part_name AS "PART_NAME",
          PBR.contract_objid AS "CONTRACT_OBJID",
          PBR.unit_code AS "UNIT_CODE",
          COALESCE((SELECT SUM(CASE WHEN (out_qty IS NULL OR out_qty = '') THEN 0
                                    ELSE out_qty::numeric END)
                    FROM inventory_mgmt_out O, inventory_mgmt S_IM
                    WHERE S_IM.part_objid = PM.objid
                      AND O.parent_objid = S_IM.objid
                      AND O.contract_mgmt_objid = PBR.contract_objid
                      AND O.unit = PBR.unit_code), 0) AS "OUT_QTY"
        FROM bom_part_qty BPQ
        LEFT OUTER JOIN part_mng PM ON PM.objid = BPQ.part_no
        LEFT OUTER JOIN part_bom_report PBR ON PBR.objid = BPQ.bom_report_objid
        WHERE BPQ.last_part_objid = $1
          AND PBR.contract_objid = $2
          AND PBR.unit_code = $3
          AND BPQ.status = 'deploy'
      ) T
`,
    [partObjId, projectObjId, unitCode],
  );

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