import { ModuleRoutes } from "@/components/module-routes";
import { IModuleClient } from "@erp/core/client";
import { AppLayout } from "@repo/rdx-ui/components";
import { Navigate, Route, createBrowserRouter, createRoutesFromElements } from "react-router-dom";
import { ErrorPage } from "../pages";
import { modules } from "../register-modules"; // Aquí ca

function groupModulesByLayout(modules: IModuleClient[]) {
  const groups: Record<string, IModuleClient[]> = {
    auth: [],
    app: [],
  };

  if (modules) {
    for (const module of modules) {
      if (typeof module.layout !== "string") continue;

      const layout = module.layout || "app";
      groups[layout] = groups[layout] || [];
      groups[layout].push(module);
    }
  }

  return groups;
}

export const getAppRouter = () => {
  const params = {
    ...import.meta.env,
  };

  const grouped = groupModulesByLayout(modules);

  return createBrowserRouter(
    createRoutesFromElements(
      <Route path='/'>
        {/* Auth Layout */}
        <Route path='/auth'>
          <Route index element={<Navigate to='login' />} />
          <Route path='*' element={<ModuleRoutes modules={grouped.auth} params={params} />} />
        </Route>

        {/* App Layout */}
        <Route element={<AppLayout />}>
          {/* Dynamic Module Routes */}
          <Route path='*' element={<ModuleRoutes modules={grouped.app} params={params} />} />

          {/* Main Layout */}
          <Route path='/dashboard' element={<ErrorPage />} />
          <Route path='/settings' element={<ErrorPage />} />
          <Route path='/catalog' element={<ErrorPage />} />
          <Route path='/quotes' element={<ErrorPage />} />
        </Route>
      </Route>
    )
  );
};
