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

// 구조 연결 (원본: partMng/relatePartInfo.do → partMngService.relatePartInfo)
// leftObjId (부모 bom_part_qty.child_objid) 아래에 rightCheckedArr(part_mng.objid 배열)를 자식으로 추가.
// 원본은 STATUS='adding' 고정 + seq는 nextval('seq_bom_qty').
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 leftObjId = String(body.leftObjId || "");                // 부모 bom_part_qty.child_objid
  const leftPartLastObjId = String(body.partObjId || body.leftPartLastObjId || "");
  const leftPartNoQty = String(body.leftPartNoQty || "");        // 부모 part_no (PARENT_PART_NO)
  const leftPartChildObjId = String(body.leftPartChildObjId || ""); // PARENT_QTY_CHILD_OBJID
  const rightCheckedArr: string[] = Array.isArray(body.rightCheckedArr) ? body.rightCheckedArr.map((s: unknown) => String(s)) : [];
  const changeType = String(body.CHANGE_TYPE || "");
  const changeOption = String(body.CHANGE_OPTION || "");

  if (!bomReportObjId) {
    return NextResponse.json({ success: false, message: "BOM_REPORT_OBJID 누락" }, { status: 400 });
  }
  if (rightCheckedArr.length === 0) {
    return NextResponse.json({ success: false, message: "추가할 Part가 없습니다." });
  }

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

    for (const rightPartObjId of rightCheckedArr) {
      const newObjId = createObjectId();
      const newChildObjId = createObjectId();

      await client.query(
        `INSERT INTO bom_part_qty (
           objid, bom_report_objid, parent_objid, child_objid,
           parent_part_no, part_no, last_part_objid,
           qty, qty_temp, status, seq, regdate, writer
         ) VALUES (
           $1, $2, $3, $4, $5, $6, $7, $8, $8, 'adding',
           nextval('seq_bom_qty'), NOW(), $9
         )`,
        [
          newObjId, bomReportObjId,
          leftObjId || null,
          newChildObjId,
          leftPartLastObjId || null,
          rightPartObjId,
          rightPartObjId,
          "1",
          user.userId,
        ],
      );

      // insertPartMngHistory (HIS_STATUS='ADD') — 원본 partMng.insertPartMngHistory
      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, 'ADD', $8::varchar,
           '', NULL, '', '', ''
         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 (원본 서비스: paramMap.leftPartNoQty)
          changeType || "",                   // $4 CHANGE_TYPE
          bomReportObjId,                     // $5 BOM_REPORT_OBJID
          leftObjId || "",                    // $6 PARENT_PART_OBJID (=leftObjId)
          leftPartChildObjId || "",           // $7 PARENT_QTY_CHILD_OBJID
          newChildObjId,                      // $8 CHILD_OBJID
          rightPartObjId,                     // $9 OBJID (part_mng.objid)
        ],
      );
    }

    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 connect:", e);
    return NextResponse.json({ success: false, message: "연결 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
