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

// 불출의뢰서 상세 (inventoryMng.getInventoryRequestMasterInfo + getInventoryMngRequestDetailList 대응)
// 원본: inventoryMng.xml line 1946, 2110
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 masterObjId = String(body.INVENTORY_REQUEST_MASTER_OBJID || body.objId || "");
  if (!masterObjId) {
    return NextResponse.json({ success: false, message: "OBJID 누락" }, { status: 400 });
  }

  const master = await queryOne(
    `SELECT
        IM.objid::text AS "OBJID",
        IM.parent_objid AS "PARENT_OBJID",
        IM.inventory_out_no AS "INVENTORY_OUT_NO",
        IM.request_date AS "REQUEST_DATE",
        IM.request_id AS "REQUEST_ID",
        IM.reception_status AS "RECEPTION_STATUS",
        IM.reception_id AS "RECEPTION_ID",
        IM.reception_date AS "RECEPTION_DATE",
        IM.outstatus AS "OUTSTATUS",
        IM.writer AS "WRITER",
        IM.regdate AS "REGDATE",
        IM.remark AS "REMARK",
        IM.contract_mgmt_objid AS "CONTRACT_MGMT_OBJID",
        IM.sign AS "SIGN",
        (SELECT project_no FROM project_mgmt P WHERE P.objid = IM.contract_mgmt_objid) AS "PROJECT_NO"
      FROM inventory_mgmt_out_master IM
      WHERE IM.objid = $1`,
    [masterObjId],
  );

  const details = await queryRows(
    `SELECT
        IMO.objid::text AS "OBJID",
        IMO.parent_objid AS "PARENT_OBJID",
        IMO.request_qty AS "REQUEST_QTY",
        IMO.out_qty AS "OUT_QTY",
        IMO.out_date AS "OUT_DATE",
        IMO.writer AS "WRITER",
        IMO.acq_user AS "ACQ_USER",
        IMO.inventory_request_master_objid AS "INVENTORY_REQUEST_MASTER_OBJID",
        IMO.sign AS "SIGN_ROW",
        IMO.contract_mgmt_objid AS "CONTRACT_MGMT_OBJID",
        IMO.unit AS "UNIT",
        (SELECT project_no FROM project_mgmt PM WHERE PM.objid = IMO.contract_mgmt_objid) AS "PROJECT_NO",
        (SELECT O.unit_no || '-' || O.task_name FROM pms_wbs_task O WHERE O.objid = IMO.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 material FROM part_mng O WHERE O.objid::varchar = IM.part_objid) AS "MATERIAL",
        (SELECT code_name FROM comm_code O
           WHERE O.code_id = COALESCE(NULLIF(IMI.location, ''), IM.location)) AS "LOCATION_NAME",
        (SELECT code_name FROM comm_code O
           WHERE O.code_id = COALESCE(NULLIF(IMI.sub_location, ''), IM.sub_location)) AS "SUB_LOCATION_NAME",
        (SELECT sign FROM inventory_mgmt_out_master O WHERE O.objid = IMO.inventory_request_master_objid) AS "SIGN",
        (SELECT user_name FROM user_info UI
          WHERE UI.user_id = (
            SELECT writer FROM inventory_mgmt_in IMI2
             WHERE IMI2.parent_objid = IMO.parent_objid
             ORDER BY regdate DESC LIMIT 1
          )) AS "RECEIVER_NAME",
        (SELECT user_name FROM user_info UI WHERE UI.user_id = IMO.acq_user) AS "ACQ_USER_NAME",
        IMI.objid AS "IN_OBJID"
      FROM inventory_mgmt_out IMO
      LEFT OUTER JOIN inventory_mgmt IM ON IM.objid = IMO.parent_objid
      LEFT OUTER JOIN inventory_mgmt_in IMI
        ON IMO.objid = ANY(STRING_TO_ARRAY(IMI.out_objid, ','))
      WHERE IMO.inventory_request_master_objid = $1
      ORDER BY IMO.regdate`,
    [masterObjId],
  );

  return NextResponse.json({ success: true, master, details });
}
