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

// partBomList.jsp UPG 매트릭스 데이터 (원본 getPartBomList.do 대응)
// product_code 선택 시: productList(SPEC) + LIST(UPG별 VC 매트릭스)
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 productCode = String(body.product_code || "");

  // 상단 SPEC 헤더 리스트 (PRODUCT_MGMT_UPG_MASTER)
  let productList: Array<Record<string, unknown>> = [];
  if (productCode) {
    productList = await queryRows(
      `SELECT PMUM.objid::text AS "MASTER_OBJID",
         PMUM.target_objid::text AS "PRODUCT_MGMT_OBJID",
         PMUM.spec_name AS "SPEC_NAME"
       FROM product_mgmt_upg_master PMUM
       WHERE PMUM.target_objid = $1::integer
       ORDER BY PMUM.objid`,
      [productCode],
    );
  }

  // UPG 코드 리스트 (unique UPG_CODE + UPG_NAME) — 각 코드에 대해 SPEC별 VC 값 매트릭스
  let upgList: Array<Record<string, unknown>> = [];
  if (productCode) {
    upgList = await queryRows(
      `SELECT DISTINCT
         PMUD.upg_code AS "UPG_CODE",
         PMUD.upg_name AS "UPG_NAME",
         PMUD.objid::text AS "CODE_ID"
       FROM product_mgmt_upg_detail PMUD
       WHERE PMUD.product_objid = $1::integer
       ORDER BY PMUD.upg_code`,
      [productCode],
    );

    // 각 UPG_CODE에 대해 SPEC별 VC 값 채우기
    for (const u of upgList) {
      const upgCode = String(u.UPG_CODE);
      const matrix = await queryRows(
        `SELECT PMUD.target_objid::text AS "MASTER_OBJID",
           PMUD.vc AS "VC",
           PMUD.upg_code || '-' ||
             (SELECT product_code FROM product_mgmt PM WHERE PM.objid = PMUD.product_objid) ||
             '-' || PMUD.vc AS "UPG_NO"
         FROM product_mgmt_upg_detail PMUD
         WHERE PMUD.product_objid = $1::integer AND PMUD.upg_code = $2
         ORDER BY PMUD.target_objid`,
        [productCode, upgCode],
      );
      productList.forEach((p, i) => {
        const hit = matrix.find((m) => String(m.MASTER_OBJID) === String(p.MASTER_OBJID));
        u[`UPG_NO${i}`] = hit ? hit.UPG_NO : "";
      });
    }
  }

  return NextResponse.json({
    productList,
    LIST: upgList,
    productListCnt: productList.length,
  });
}
