import {
  createRouter,
  RootRoute,
  Route,
  AnyRoute,
} from "@tanstack/react-router";
import { RootLayout } from "./RouteLayout";
import { getRoutes } from "./routeConfigs";
import NotFound from "../Pages/NotFound";
import { Auth } from "../Pages/Auth";
import { ItemWithSubItems } from "../types/userPermissions";

export const rootRoute = new RootRoute({
  component: RootLayout,
});

export function makeRouter(auth: string | null, roles: ItemWithSubItems[]) {
  const routeConfigs = getRoutes(auth, roles);

  const childRoutes: AnyRoute[] = routeConfigs.map(
    ({ path, component }) =>
      new Route({
        getParentRoute: () => rootRoute,
        path,
        component,
      }) as AnyRoute
  );

  const notFoundRoute = new Route({
    getParentRoute: () => rootRoute,
    path: "*",
    component: auth ? NotFound : Auth,
  });

  const routeTree = rootRoute.addChildren([...childRoutes, notFoundRoute]);

  return createRouter({
    routeTree,
    defaultPreload: "intent",
  });
}
