import type { IModuleClient } from "@erp/core/client";
import { AppLayout } from "@repo/rdx-ui/components";
import { Navigate, Route, createBrowserRouter, createRoutesFromElements } from "react-router-dom";

import { ModuleRoutes } from "@/components/module-routes";

import { ErrorPage, LoginForm } 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 element={<Navigate to="login" />} index />
          <Route element={<LoginForm />} path="login" />
          <Route element={<ModuleRoutes modules={grouped.auth} params={params} />} path="*" />
        </Route>

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

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