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

// 구조등록 팝업 좌측 트리 (원본: partMng/structurePopupLeft.do)
// bomReportObjId 기준 bom_part_qty 재귀 트리 + 파일카운트 + PART_MNG 정보
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.bomReportObjId || body.objId || "");
  if (!bomReportObjId) return NextResponse.json({ RESULTLIST: [], HEADER: {} });

  const header = await queryOne(
    `SELECT T.objid::text AS "OBJID",
       T.status AS "STATUS",
       T.revision AS "REV",
       T.note AS "NOTE",
       T.deploy_date AS "DEPLOY_DATE",
       (SELECT supply_name FROM supply_mng O WHERE O.objid::varchar = T.customer_objid) AS "CUSTOMER_NAME",
       (SELECT project_no FROM project_mgmt O WHERE O.objid = T.contract_objid) AS "PROJECT_NO",
       (SELECT customer_project_name FROM project_mgmt O WHERE O.objid = T.contract_objid) AS "CUSTOMER_PROJECT_NAME",
       (SELECT O.unit_no || '-' || O.task_name FROM pms_wbs_task O WHERE O.objid = T.unit_code) AS "UNIT_NAME"
     FROM part_bom_report T WHERE T.objid = $1`,
    [bomReportObjId],
  );

  const rows = await queryRows(
    `WITH RECURSIVE VIEW_BOM AS (
       SELECT
         A.bom_report_objid, A.objid, A.parent_objid, A.child_objid,
         A.parent_part_no, A.part_no, A.last_part_objid,
         A.qty, A.qty_temp, A.status, A.regdate, A.seq,
         1::int AS lev,
         ARRAY[A.child_objid::text] AS path,
         ARRAY[A.part_no::text] AS parent_parts_arr
       FROM bom_part_qty A
       WHERE (A.parent_objid IS NULL OR A.parent_objid = '')
         AND A.bom_report_objid = $1
         AND (A.status NOT IN ('deleting', 'deleted') OR A.status IS NULL)
       UNION ALL
       SELECT
         B.bom_report_objid, B.objid, B.parent_objid, B.child_objid,
         B.parent_part_no, B.part_no, B.last_part_objid,
         B.qty, B.qty_temp, B.status, B.regdate, B.seq,
         V.lev + 1,
         V.path || B.child_objid::text,
         V.parent_parts_arr || B.part_no::text
       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.status NOT IN ('deleting', 'deleted') OR B.status IS NULL)
     ),
     MAX_LEV AS (SELECT MAX(lev) AS max_level FROM VIEW_BOM)
     SELECT
       V.objid::text AS "OBJID",
       V.bom_report_objid AS "BOM_REPORT_OBJID",
       V.parent_objid AS "PARENT_OBJID",
       V.child_objid AS "CHILD_OBJID",
       V.parent_part_no AS "PARENT_PART_NO",
       V.last_part_objid AS "LAST_PART_OBJID",
       V.last_part_objid AS "BOM_LAST_PART_OBJID",
       V.qty AS "QTY",
       V.qty_temp AS "QTY_TEMP",
       V.status AS "STATUS",
       V.seq AS "SEQ",
       V.lev AS "LEVEL",
       (SELECT max_level FROM MAX_LEV) AS "MAX_LEVEL",
       (CASE WHEN EXISTS (SELECT 1 FROM bom_part_qty C WHERE C.parent_objid = V.child_objid
                            AND C.bom_report_objid = V.bom_report_objid) THEN 0 ELSE 1 END) AS "LEAF",
       array_to_string(V.parent_parts_arr, ',') AS "PARENT_PARTS",
       P.objid::text AS "PART_OBJID",
       P.part_no AS "PART_NO",
       P.part_name AS "PART_NAME",
       P.revision AS "REVISION",
       P.material AS "MATERIAL",
       P.spec AS "SPEC",
       P.maker AS "MAKER",
       P.eo_no AS "EO_NO",
       P.eo_date AS "EO_DATE",
       P.part_type AS "PART_TYPE",
       (SELECT code_name FROM comm_code WHERE code_id = P.part_type) AS "PART_TYPE_TITLE",
       (SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '3D_CAD') AS "CU01_CNT",
       (SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '2D_DRAWING_CAD') AS "CU02_CNT",
       (SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '2D_PDF_CAD') AS "CU03_CNT"
     FROM VIEW_BOM V
       LEFT JOIN part_mng P ON P.objid::text = V.last_part_objid
     ORDER BY V.path, V.seq NULLS LAST, V.regdate`,
    [bomReportObjId],
  );

  return NextResponse.json({ RESULTLIST: rows, HEADER: header ?? {} });
}
