// admin-panel 좌측 사이드바 메뉴 — [관리자] 루트 아래 status='active' 자식 트리
import { NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

export async function GET() {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  // [관리자] 루트 찾기 (menu_name_kor='관리자' + parent=0)
  const rootRows = await queryRows<{ OBJID: string }>(
    `SELECT OBJID::text AS "OBJID" FROM menu_info
     WHERE PARENT_OBJ_ID = 0 AND MENU_NAME_KOR = '관리자'
     LIMIT 1`
  );
  if (rootRows.length === 0) return NextResponse.json({ groups: [] });
  const rootId = rootRows[0].OBJID;

  // [관리자] 자식(섹션) + 손자(아이템)
  const rows = await queryRows<{ OBJID: string; PARENT_OBJ_ID: string; NAME: string; SEQ: string; URL: string }>(
    `SELECT OBJID::text AS "OBJID", PARENT_OBJ_ID::text AS "PARENT_OBJ_ID",
            MENU_NAME_KOR AS "NAME", SEQ::text AS "SEQ",
            COALESCE(MENU_URL, '') AS "URL"
     FROM menu_info
     WHERE COALESCE(STATUS, '') = 'active'
       AND (PARENT_OBJ_ID = $1::numeric OR PARENT_OBJ_ID IN (
         SELECT OBJID FROM menu_info WHERE PARENT_OBJ_ID = $1::numeric AND COALESCE(STATUS,'') = 'active'
       ))
     ORDER BY SEQ ASC`,
    [rootId]
  );

  const sections = rows.filter((r) => r.PARENT_OBJ_ID === rootId);
  const items = rows.filter((r) => r.PARENT_OBJ_ID !== rootId);
  const groups = sections.map((s) => ({
    objid: s.OBJID,
    label: s.NAME,
    items: items
      .filter((i) => i.PARENT_OBJ_ID === s.OBJID)
      .map((i) => ({ objid: i.OBJID, label: i.NAME, url: i.URL })),
  })).filter((g) => g.items.length > 0);

  return NextResponse.json({ groups, rootId });
}
