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

// 불출의뢰/자재이동 팝업에서 선택된 inventory_mgmt OBJID들의 상세정보
// 원본: inventoryMng.getInventoryMngRequestList (inventoryMng.xml line 1665)
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 checkArrRaw = body.checkArr;
  const arr: string[] = Array.isArray(checkArrRaw)
    ? checkArrRaw.map(String)
    : String(checkArrRaw || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
  if (arr.length === 0) {
    return NextResponse.json({ RESULTLIST: [] });
  }

  const placeholders = arr.map((_, i) => `$${i + 1}`).join(",");

  const rows = await queryRows(
    `SELECT
        TBL.*,
        (COALESCE(TBL."DESIGN_QTY1", 0) * COALESCE(TBL."QTY1", 0)
          * COALESCE(NULLIF(TBL."QTY3", '')::numeric, 1)) AS "DESIGN_QTY"
      FROM (
        SELECT
          IM.objid::text AS "OBJID",
          IM.part_objid AS "PART_OBJID",
          (SELECT project_no FROM project_mgmt O WHERE O.objid = IM.contract_objid) AS "PROJECT_NO",
          CASE WHEN IMI.receipt_qty IS NULL OR IMI.receipt_qty = '' THEN 0
               ELSE (IMI.receipt_qty::numeric - COALESCE(NULLIF(IMI.out_qty, '')::numeric, 0) - COALESCE(NULLIF(IMI.move_qty, '')::numeric, 0))
          END AS "USE_CNT",
          (SELECT SUM(CASE WHEN (receipt_qty IS NULL OR receipt_qty = '') THEN 0 ELSE receipt_qty::numeric END)
           FROM inventory_mgmt_in O WHERE O.parent_objid = IM.objid) AS "QTY",
          (SELECT O.unit_no || '-' || O.task_name FROM pms_wbs_task O WHERE O.objid = IM.unit) AS "UNIT_NAME",
          (SELECT part_no FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "PART_NO",
          (SELECT part_name FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "PART_NAME",
          (SELECT spec FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "SPEC",
          (SELECT maker FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "MAKER",
          (SELECT (SELECT code_name FROM comm_code CC WHERE CC.code_id = part_type)
             FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "PART_TYPE_NAME",
          (SELECT part_type FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "PART_TYPE",
          (SELECT code_name FROM comm_code O WHERE O.code_id = IM.cls_cd) AS "CLS_CD_NAME",
          IM.cls_cd AS "CLS_CD",
          (SELECT code_name FROM comm_code O WHERE O.code_id = IM.cau_cd) AS "CAU_CD_NAME",
          IM.cau_cd AS "CAU_CD",
          (SELECT material FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "MATERIAL",
          IMI.location AS "LOCATION",
          (SELECT code_name FROM comm_code O WHERE O.code_id = IMI.location) AS "LOCATION_NAME",
          IMI.sub_location AS "SUB_LOCATION",
          (SELECT code_name FROM comm_code O WHERE O.code_id = IMI.sub_location) AS "SUB_LOCATION_NAME",
          IM.reg_date AS "REG_DATE",
          IM.price AS "PRICE",
          (SELECT user_name FROM user_info O WHERE O.user_id = IM.writer) AS "WRITER_NAME",
          IM.contract_objid AS "CONTRACT_OBJID",
          IM.unit AS "UNIT",
          IMI.objid AS "IN_OBJID",
          PBR.objid AS "BOM_REPORT_OBJID",
          (SELECT SUM(COALESCE(NULLIF(BPQ.qty, '')::numeric, 0))
             FROM bom_part_qty BPQ
             WHERE BPQ.bom_report_objid = PBR.objid
               AND BPQ.last_part_objid = IM.part_objid
               AND BPQ.status IN ('beforeEdit', 'editing', 'deleting', 'deploy')) 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, '') = ''
               AND BPQ.status IN ('beforeEdit', 'editing', 'deleting', 'deploy')) 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 = (
                 SELECT parent_objid FROM bom_part_qty BPQ
                  WHERE BPQ.bom_report_objid = PBR.objid
                    AND BPQ.last_part_objid = IM.part_objid
                    AND BPQ.status IN ('beforeEdit', 'editing', 'deleting', 'deploy')
                  LIMIT 1
               )) AS "QTY3",
          (SELECT SUM(COALESCE(NULLIF(pre_booking_qty, '')::numeric, 0))
             FROM sales_bom_report_part SBRP
             WHERE SBRP.parent_objid = PBR.objid AND SBRP.part_objid = IM.part_objid) AS "PRE_BOOKING_QTY",
          IMI.out_qty AS "OUT_QTY"
        FROM inventory_mgmt IM
        LEFT OUTER JOIN inventory_mgmt_in IMI ON IMI.parent_objid = IM.objid
        LEFT OUTER JOIN part_bom_report PBR
          ON PBR.contract_objid = IM.contract_objid AND PBR.unit_code = IM.unit
        WHERE IM.objid IN (${placeholders})
      ) TBL
     WHERE COALESCE("USE_CNT", 0) != 0
     ORDER BY "PART_NO"
`,
    arr,
  );

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