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

// 구조 연결 해제 (원본: partMng/deleteStatusPartRelateInfo.do → partMngService.deleteStatusPartRelateInfo)
// 1) insertPartMngHistoryWhenDelPartRelation (HIS_STATUS='DEL') — 재귀 DEL 이력
// 2) deletePartRelateInfoHis — adding 상태의 하위 이력 제거
// 3) deleteStatusPartRelateInfo — 재귀 논리 삭제 (status='deleting')
// 4) 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 leftObjId = String(body.leftObjId || ""); // bom_part_qty.child_objid
  const changeType = String(body.CHANGE_TYPE || "");
  const changeOption = String(body.CHANGE_OPTION || "");

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

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

    // 1) DEL 이력 — 재귀 서브트리 전체를 part_mng_history에 기록
    await client.query(
      `WITH RECURSIVE VIEW_BOM AS (
         SELECT A.objid, A.child_objid, A.parent_objid, A.bom_report_objid
           FROM bom_part_qty A
           WHERE A.child_objid = $9::varchar AND A.bom_report_objid = $5::varchar
         UNION ALL
         SELECT B.objid, B.child_objid, B.parent_objid, B.bom_report_objid
           FROM bom_part_qty B
           JOIN VIEW_BOM V ON B.parent_objid = V.child_objid
             AND V.bom_report_objid = B.bom_report_objid
             AND B.bom_report_objid = $5::varchar
             AND B.status NOT IN ('deleting', 'deleted')
       )
       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
       )
       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, $8::varchar, Q.child_objid,
         ''
       FROM bom_part_qty Q
         INNER JOIN part_mng P ON Q.last_part_objid = P.objid
       WHERE Q.objid IN (SELECT objid FROM VIEW_BOM)`,
      [
        changeOption || "",  // $1 CHANGE_OPTION
        user.userId,         // $2 WRITER
        "",                  // $3 PARENT_PART_NO (원본 서비스는 "")
        changeType || "",    // $4 CHANGE_TYPE
        bomReportObjId,      // $5 BOM_REPORT_OBJID
        "",                  // $6 PARENT_PART_OBJID (원본 서비스는 "")
        "",                  // $7 PARENT_QTY_CHILD_OBJID (원본 서비스는 "")
        "DEL",               // $8 HIS_STATUS
        leftObjId,           // $9 leftObjId (재귀 시작점)
      ],
    );

    // 2) deletePartRelateInfoHis — 하위 트리 중 'adding' 상태인 행의 이력만 삭제
    await client.query(
      `WITH RECURSIVE VIEW_BOM AS (
         SELECT A.child_objid, A.parent_objid, A.bom_report_objid, A.status
           FROM bom_part_qty A
           WHERE A.child_objid = $2 AND A.bom_report_objid = $1
         UNION ALL
         SELECT B.child_objid, B.parent_objid, B.bom_report_objid, B.status
           FROM bom_part_qty B
           JOIN VIEW_BOM V ON B.parent_objid = V.child_objid
             AND V.bom_report_objid = B.bom_report_objid
             AND B.bom_report_objid = $1
       )
       DELETE FROM part_mng_history
        WHERE qty_child_objid IN (
          SELECT child_objid FROM VIEW_BOM V WHERE V.status = 'adding'
        )`,
      [bomReportObjId, leftObjId],
    );

    // 3) deleteStatusPartRelateInfo — 재귀 논리 삭제
    await client.query(
      `WITH RECURSIVE VIEW_BOM(objid, child_objid) AS (
         SELECT A.objid, A.child_objid FROM bom_part_qty A
           WHERE A.child_objid = $2 AND A.bom_report_objid = $1
         UNION ALL
         SELECT B.objid, B.child_objid FROM bom_part_qty B
           JOIN VIEW_BOM V ON B.parent_objid = V.child_objid
           WHERE B.bom_report_objid = $1
             AND B.status NOT IN ('deleting', 'deleted')
       )
       UPDATE bom_part_qty
          SET edit_date = NOW(), status = 'deleting'
        WHERE objid IN (SELECT objid FROM VIEW_BOM)`,
      [bomReportObjId, leftObjId],
    );

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