import { describe, expect, test } from "vitest";
import { MENU_CODE_VALUES, PERMISSION_CODES } from "@/app/permissions";
import { fallbackNavigation } from "@/app/navigation/menu";
import { adminRoutes } from "@/app/router/routeConfig";

type TestNavItem = {
  children?: TestNavItem[];
  code: string;
  path?: string;
  permissionCode?: string;
};

describe("admin route config", () => {
  test("uses unique paths, page keys and menu codes", () => {
    expect(new Set(adminRoutes.map((route) => route.path)).size).toBe(adminRoutes.length);
    expect(new Set(adminRoutes.map((route) => route.pageKey)).size).toBe(adminRoutes.length);
    expect(new Set(adminRoutes.map((route) => route.menuCode)).size).toBe(adminRoutes.length);
  });

  test("uses known menu codes and permission codes", () => {
    const menuCodes = new Set(MENU_CODE_VALUES);
    const permissions = new Set(PERMISSION_CODES);

    for (const route of adminRoutes) {
      expect(menuCodes.has(route.menuCode)).toBe(true);
      expect(permissions.has(route.permission)).toBe(true);
    }
  });

  test("fallback leaf menus match routes", () => {
    const routesByMenuCode = new Map<string, (typeof adminRoutes)[number]>(
      adminRoutes.map((route) => [route.menuCode, route])
    );

    for (const item of flattenNavigation(fallbackNavigation as TestNavItem[]).filter((navItem) => navItem.path)) {
      const route = routesByMenuCode.get(item.code);
      expect(route?.path).toBe(item.path);
      expect(route?.permission).toBe(item.permissionCode);
    }
  });
});

function flattenNavigation(items: TestNavItem[]): TestNavItem[] {
  return items.flatMap((item) => [item, ...flattenNavigation(item.children || [])]);
}
