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

// main/getmenu.do 대응 — 사이드 메뉴 조회 (권한 그룹 필터 적용)
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 menuObjId = body.MENUOBJID || "";

  // 로그인한 사용자의 권한 그룹에 매핑된 메뉴만 노출 (자식이 권한에 있으면 부모 자동 표시).
  // isAdmin 같은 백도어는 두지 않음 — 모든 사용자는 권한 그룹 매핑대로 동적으로 메뉴를 받는다.
  const rows = await queryRows(
    `SELECT MI.OBJID::text AS "objid",
            MI.MENU_NAME_KOR AS "menuNameKor",
            MI.MENU_NAME_ENG AS "menuNameEng",
            COALESCE(MI.MENU_URL, '') AS "menuUrl",
            MI.PARENT_OBJ_ID::text AS "parentObjId",
            MI.SEQ::text AS "menuOrder",
            CASE WHEN MI.PARENT_OBJ_ID = $1::numeric THEN '1' ELSE '2' END AS "level"
     FROM MENU_INFO MI
     WHERE COALESCE(MI.STATUS, '') = 'active'
       AND (MI.PARENT_OBJ_ID = $1::numeric
            OR MI.PARENT_OBJ_ID IN (SELECT OBJID FROM MENU_INFO WHERE PARENT_OBJ_ID = $1::numeric AND COALESCE(STATUS, '') = 'active'))
       AND (
         MI.OBJID IN (
           SELECT ASM.menu_objid
           FROM authority_sub_user ASU
           JOIN authority_sub_menu ASM ON ASM.master_objid = ASU.master_objid
           WHERE ASU.user_id = $2::text
         )
         OR EXISTS (
           SELECT 1 FROM menu_info CH
           WHERE CH.parent_obj_id = MI.objid
             AND CH.objid IN (
               SELECT ASM.menu_objid
               FROM authority_sub_user ASU
               JOIN authority_sub_menu ASM ON ASM.master_objid = ASU.master_objid
               WHERE ASU.user_id = $2::text
             )
         )
       )
     ORDER BY MI.SEQ`,
    [menuObjId, user.userId]
  );

  return NextResponse.json({ RESULT: rows });
}
