import { type ReactNode } from 'react';
import { createBrowserRouter, type RouteObject } from 'react-router-dom';
import { appRoutes, type RouteConfig } from './config';
import { ProtectedRoute } from '@/components/routes/ProtectedRoute';

/**
 * A recursive function to map our custom route config to the format
 * that react-router-dom expects, applying layouts and guards.
 */
function mapRoutes(routes: RouteConfig[]): RouteObject[] {
  return routes.map((route) => {
    // Remove the suspense from here and move to layout outlet
    // Avoid loading layout for rendering different children
    let element: ReactNode = route.element;

    if (route.authorize) {
      element = <ProtectedRoute>{element}</ProtectedRoute>;
    }

    return {
      path: route.path,
      element: element,
      ...(route.children && { children: mapRoutes(route.children) }),
    };
  });
}

export const router = createBrowserRouter(mapRoutes(appRoutes));
