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

// 구조 연결 변경 (원본: partMng/changeRelatePartInfo.do → partMngService.changeRelatePartInfo)
// 1) UPDATE BOM_PART_QTY SET LAST_PART_OBJID = #{RIGHT_OBJID} WHERE BOM_REPORT_OBJID = ? AND OBJID = ?
// 2) insertPartMngHistory (HIS_STATUS='CHANGE')
// 3) changeStatusBomReport
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 bomReportObjId = String(body.BOM_REPORT_OBJID || body.OBJID || "");
  const bomObjId = String(body.B_OBJID || body.leftPartBomQtyObjId || ""); // bom_part_qty.objid
  const rightObjId = String(body.rightObjId || body.rightPartObjId || "");  // 새 part_mng.objid
  const leftPartObjid = String(body.leftPartObjid || "");                   // 기존 part_mng.objid (PART_MNG의 P)
  const leftObjId = String(body.leftObjId || "");                           // parent bom_part_qty.child_objid
  const leftPartNoQty = String(body.leftPartNoQty || "");
  const leftPartChildObjId = String(body.leftPartChildObjId || "");
  const rightPartNo = String(body.rightPartNo || "");
  const rightPartRev = String(body.rightPartRev || "");
  const changeType = String(body.CHANGE_TYPE || "");
  const changeOption = String(body.CHANGE_OPTION || "");

  if (!bomReportObjId || !bomObjId || !rightObjId) {
    return NextResponse.json({ success: false, message: "필수 파라미터 누락" }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 1) bom_part_qty.last_part_objid 교체
    await client.query(
      `UPDATE bom_part_qty
          SET last_part_objid = $1
        WHERE bom_report_objid = $2 AND objid = $3`,
      [rightObjId, bomReportObjId, bomObjId],
    );

    // 2) insertPartMngHistory (HIS_STATUS='CHANGE')
    const newChildObjId = createObjectId(); // 원본 서비스: 새 CHILD_OBJID로 세팅
    await client.query(
      `INSERT INTO part_mng_history (
         objid, product_mgmt_objid, upg_no, part_no, part_name, unit, qty,
         spec, material, weight, part_type, remark, es_spec, ms_spec,
         change_option, design_apply_point, management_flag, revision, status,
         reg_date, edit_date, writer, is_last, eo_no, eo_temp,
         excel_upload_seq, sourcing_code, sub_material, parent_part_no,
         design_date, eo_date, deploy_date,
         thickness, width, height, out_diameter, in_diameter, length, supply_code,
         change_type, contract_objid, maker, qty_temp,
         bom_report_objid, parent_part_objid, parent_qty_child_objid,
         bom_qty_status, his_reg_date, his_writer, his_status, qty_child_objid,
         bom_status, bom_deploy_date, chg_part_objid, chg_part_no, chg_part_rev
       )
       SELECT
         P.objid::numeric, P.product_mgmt_objid, P.upg_no, P.part_no, P.part_name, P.unit, Q.qty,
         P.spec, P.material, P.weight, P.part_type, P.remark, P.es_spec, P.ms_spec,
         COALESCE(NULLIF($1::varchar, ''), P.change_option),
         P.design_apply_point, P.management_flag, P.revision, P.status,
         P.reg_date, NOW(), $2::varchar, P.is_last, P.eo_no, P.eo_temp,
         P.excel_upload_seq, P.sourcing_code, P.sub_material,
         COALESCE(NULLIF($3::varchar, ''), Q.parent_part_no),
         P.design_date, P.eo_date, P.deploy_date,
         P.thickness, P.width, P.height, P.out_diameter, P.in_diameter, P.length, P.supply_code,
         COALESCE(NULLIF($4::varchar, ''), P.change_type),
         P.contract_objid, P.maker, Q.qty_temp,
         COALESCE(NULLIF($5::varchar, ''), Q.bom_report_objid),
         COALESCE(NULLIF($6::varchar, ''), Q.parent_part_no),
         COALESCE(NULLIF($7::varchar, ''), Q.parent_objid),
         Q.status, NOW(), $2::varchar, 'CHANGE', $8::varchar,
         '', NULL, $10::varchar, $11::varchar, $12::varchar
       FROM part_mng P
         LEFT OUTER JOIN bom_part_qty Q
           ON Q.child_objid = $8::varchar
          AND P.part_no IN (SELECT PM2.part_no FROM part_mng PM2 WHERE PM2.objid = Q.part_no)
       WHERE P.objid = $9::varchar`,
      [
        changeOption || "",           // $1 CHANGE_OPTION
        user.userId,                  // $2 WRITER
        leftPartNoQty || "",          // $3 PARENT_PART_NO
        changeType || "",             // $4 CHANGE_TYPE
        bomReportObjId,               // $5 BOM_REPORT_OBJID
        leftObjId || "",              // $6 PARENT_PART_OBJID
        leftPartChildObjId || "",     // $7 PARENT_QTY_CHILD_OBJID
        newChildObjId,                // $8 CHILD_OBJID (JOIN + qty_child_objid)
        leftPartObjid || rightObjId,  // $9 OBJID (원본 서비스: leftPartObjid)
        rightObjId,                   // $10 CHG_PART_OBJID
        rightPartNo,                  // $11 CHG_PART_NO
        rightPartRev,                 // $12 CHG_PART_REV
      ],
    );

    // 3) changeStatusBomReport
    await client.query(
      `UPDATE part_bom_report
          SET status = CASE WHEN status != 'create' THEN 'changeDesign' ELSE status END
        WHERE objid = $1`,
      [bomReportObjId],
    );

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "변경되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("bom change:", e);
    return NextResponse.json({ success: false, message: "변경 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
