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

// UPG 리스트 (원본: common.getProductUPGNEWselect)
// PRODUCT_MGMT_OBJID 기준 UPG 콤보박스 옵션
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ RESULTLIST: [] });

  const body = await request.json().catch(() => ({}));
  const productMgmtObjId = String(body.PRODUCT_MGMT_OBJID || body.product_mgmt_objid || "");
  if (!productMgmtObjId) return NextResponse.json({ RESULTLIST: [] });

  const rows = await queryRows(
    `SELECT DISTINCT
       PMUD.upg_code || '-' ||
         (SELECT product_code FROM product_mgmt PM WHERE PM.objid = PMUD.product_objid) ||
         '-' || PMUD.vc AS "CODE",
       COALESCE(
         (SELECT code_name FROM comm_code CC WHERE CC.ext_val = PMUD.upg_code LIMIT 1),
         PMUD.upg_name
       ) AS "NAME"
     FROM product_mgmt_upg_detail PMUD
     WHERE PMUD.vc != ''
       AND PMUD.product_objid = $1::integer
     ORDER BY "CODE"`,
    [productMgmtObjId],
  );
  return NextResponse.json({ RESULTLIST: rows });
}
