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

// BOM 구조 트리 조회 - bom_report_objid 기준 계층 + PART 정보
// (setStructurePopupMainFS 및 bom-ascending 용)
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 || "");

  let info: Record<string, unknown> | null = null;
  if (bomReportObjId) {
    info = await queryOne(
      `SELECT T.objid::text AS "OBJID",
         T.status AS "STATUS",
         T.revision AS "REVISION",
         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 parts = bomReportObjId
    ? await queryRows(
        `SELECT Q.objid::text AS "OBJID",
           Q.parent_part_no AS "PARENT_PART_NO",
           Q.last_part_objid AS "PART_OBJID",
           Q.qty AS "QTY",
           Q.status AS "Q_STATUS",
           P.part_no AS "PART_NO",
           P.part_name AS "PART_NAME",
           P.material AS "MATERIAL",
           P.spec AS "SPEC",
           P.maker AS "MAKER",
           P.revision AS "REVISION",
           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",
           P.remark AS "REMARK",
           (SELECT part_no || ' ' || part_name FROM part_mng SP WHERE SP.objid = Q.parent_part_no) AS "PARENT_PART_INFO"
         FROM bom_part_qty Q
           LEFT JOIN part_mng P ON P.objid = Q.last_part_objid
         WHERE Q.bom_report_objid = $1
         ORDER BY Q.parent_part_no, P.part_no`,
        [bomReportObjId],
      )
    : [];

  return NextResponse.json({ RESULTLIST: parts, HEADER: info ?? {} });
}
