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

// 원본: salesMng.salesBomReportPartList — BOM 트리(재귀) + 기존 구매BOM(sales_bom_report_part) 매핑
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 parentObjId = String(body.parent_objId || body.bomReportObjId || "");
  if (!parentObjId) return NextResponse.json({ RESULTLIST: [] });

  const sql = `
    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.regdate, A.seq,
             1 AS lev,
             ARRAY[A.child_objid::text] AS path
        FROM bom_part_qty A
       WHERE (A.parent_objid IS NULL OR A.parent_objid = '')
         AND A.bom_report_objid = $1
      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.regdate, B.seq,
             V.lev + 1,
             V.path || B.child_objid::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
       WHERE NOT (B.child_objid = ANY(V.path))
    )
    SELECT V.bom_report_objid::text AS "PARENT_OBJID",
           V.part_no AS "PART_OBJID",
           V.child_objid AS "CHILD_OBJID",
           V.parent_part_no AS "PARENT_PART_NO",
           V.last_part_objid AS "LAST_PART_OBJID",
           V.qty AS "QTY",
           V.lev AS "LEV",
           V.seq AS "SEQ",
           (SELECT MAX(lev) FROM VIEW_BOM) AS "MAX_LEV",
           PM.objid::text AS "OBJID_PART",
           PM.part_no AS "PART_NO",
           PM.part_name AS "PART_NAME",
           PM.spec AS "SPEC",
           PM.post_processing AS "POST_PROCESSING",
           PM.maker AS "MAKER",
           PM.remark AS "REMARK",
           PM.revision AS "REVISION",
           PM.eo_no AS "EO_NO",
           (SELECT code_name FROM comm_code WHERE code_id = PM.part_type LIMIT 1) AS "PART_TYPE_NAME",
           SP.objid::text AS "OBJID",
           SP.price AS "PRICE",
           SP.supply_objid AS "SUPPLY_OBJID",
           (SELECT supply_name FROM admin_supply_mng WHERE objid::text = SP.supply_objid LIMIT 1) AS "SUPPLY_NAME",
           SP.price1 AS "PRICE1",
           SP.supply_objid1 AS "SUPPLY_OBJID1",
           (SELECT supply_name FROM admin_supply_mng WHERE objid::text = SP.supply_objid1 LIMIT 1) AS "SUPPLY_NAME1",
           SP.price2 AS "PRICE2",
           SP.supply_objid2 AS "SUPPLY_OBJID2",
           (SELECT supply_name FROM admin_supply_mng WHERE objid::text = SP.supply_objid2 LIMIT 1) AS "SUPPLY_NAME2",
           SP.price3 AS "PRICE3",
           SP.supply_objid3 AS "SUPPLY_OBJID3",
           (SELECT supply_name FROM admin_supply_mng WHERE objid::text = SP.supply_objid3 LIMIT 1) AS "SUPPLY_NAME3",
           SP.price4 AS "PRICE4",
           SP.supply_objid4 AS "SUPPLY_OBJID4",
           (SELECT supply_name FROM admin_supply_mng WHERE objid::text = SP.supply_objid4 LIMIT 1) AS "SUPPLY_NAME4",
           SP.price_sum AS "PRICE_SUM"
      FROM VIEW_BOM V
      LEFT OUTER JOIN sales_bom_report_part SP
        ON SP.parent_objid = $1 AND SP.bom_part_qty_objid = V.child_objid
      LEFT OUTER JOIN part_mng PM
        ON COALESCE(V.last_part_objid, V.part_no) = PM.objid::varchar
     ORDER BY V.path, V.regdate
  `;

  try {
    const rows = await queryRows(sql, [parentObjId]);
    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  } catch (e) {
    console.error("purchase/bom tree:", e);
    return NextResponse.json({ success: false, message: "조회 중 오류가 발생했습니다." }, { status: 500 });
  }
}
