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

// 특정 권한그룹이 가진 메뉴 OBJID 목록 + 전체 메뉴 트리
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { masterObjid } = await request.json().catch(() => ({}));

  // 전체 메뉴 트리
  const menus = await queryRows(`
    SELECT objid::text AS "OBJID",
           parent_obj_id::text AS "PARENT_OBJ_ID",
           menu_name_kor AS "MENU_NAME_KOR",
           menu_url AS "MENU_URL",
           seq::int AS "SEQ",
           menu_type::int AS "MENU_TYPE",
           COALESCE(status,'active') AS "STATUS"
    FROM menu_info
    ORDER BY menu_type, seq
  `);

  // 그룹이 가진 메뉴 OBJID 목록
  let assigned: string[] = [];
  if (masterObjid) {
    const rows = await queryRows<{ MENU_OBJID: string }>(
      `SELECT menu_objid::text AS "MENU_OBJID" FROM authority_sub_menu WHERE master_objid = $1::numeric`,
      [masterObjid]
    );
    assigned = rows.map((r) => r.MENU_OBJID);
  }

  return NextResponse.json({ success: true, MENULIST: menus, ASSIGNED: assigned });
}
