import { Navigate, Route, Routes } from "react-router-dom";
import { AdminLayout } from "@/app/layout/AdminLayout.jsx";
import { DeferredPage } from "@/app/router/DeferredPage.jsx";
import { RequireAppScope, RequireAuth, RequirePermission } from "@/app/router/guards.jsx";
import { adminRoutes, defaultAdminPath, publicRoutes } from "@/app/router/routeConfig";
import { AppUserDetailProvider } from "@/features/app-users/components/AppUserDetailProvider.jsx";

function App() {
  return (
    <AppUserDetailProvider>
      <Routes>
        {publicRoutes.map((route) => (
          <Route key={route.path} path={route.path} element={<DeferredPage route={route} />} />
        ))}
        <Route element={<RequireAuth />}>
          <Route element={<AdminLayout />}>
            <Route index element={<Navigate to={defaultAdminPath} replace />} />
            {adminRoutes.map((route) => (
              <Route
                key={route.path}
                path={route.path}
                element={
                  <RequirePermission code={route.permission}>
                    {route.path === defaultAdminPath ? (
                      <DeferredPage route={route} />
                    ) : (
                      <RequireAppScope>
                        <DeferredPage route={route} />
                      </RequireAppScope>
                    )}
                  </RequirePermission>
                }
              />
            ))}
          </Route>
        </Route>
        <Route path="*" element={<Navigate to={defaultAdminPath} replace />} />
      </Routes>
    </AppUserDetailProvider>
  );
}

export default App;
