import { Routes, Route, Navigate } from 'react-router';
import { LoginPage } from './auth/LoginPage';
import { CallbackPage } from './auth/CallbackPage';
import { ProtectedRoute } from './auth/ProtectedRoute';
import { OrgResolver } from './auth/OrgResolver';
import { Layout } from './components/Layout';
import { RequireScope } from './components/RequireScope';
import { useScopes } from './auth/useScopes';

import { VendorTenantsPage } from './pages/vendor/VendorTenantsPage';
import { CreateTenantPage } from './pages/vendor/CreateTenantPage';
import { TenantDetailPage } from './pages/vendor/TenantDetailPage';
import { TenantDashboardPage } from './pages/tenant/TenantDashboardPage';
import { TenantLicensePage } from './pages/tenant/TenantLicensePage';
import { OidcConfigPage } from './pages/tenant/OidcConfigPage';
import { TeamPage } from './pages/tenant/TeamPage';
import { SettingsPage } from './pages/tenant/SettingsPage';

function LandingRedirect() {
  const scopes = useScopes();
  if (scopes.has('platform:admin')) {
    return <Navigate to="/vendor/tenants" replace />;
  }
  return <Navigate to="/tenant" replace />;
}

export function AppRouter() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route path="/callback" element={<CallbackPage />} />
      <Route element={<ProtectedRoute />}>
        <Route element={<OrgResolver />}>
          <Route element={<Layout />}>
            {/* Vendor console */}
            <Route path="/vendor/tenants" element={
              <RequireScope scope="platform:admin" fallback={<Navigate to="/tenant" replace />}>
                <VendorTenantsPage />
              </RequireScope>
            } />
            <Route path="/vendor/tenants/new" element={
              <RequireScope scope="platform:admin" fallback={<Navigate to="/tenant" replace />}>
                <CreateTenantPage />
              </RequireScope>
            } />
            <Route path="/vendor/tenants/:id" element={
              <RequireScope scope="platform:admin" fallback={<Navigate to="/tenant" replace />}>
                <TenantDetailPage />
              </RequireScope>
            } />

            {/* Tenant portal */}
            <Route path="/tenant" element={<TenantDashboardPage />} />
            <Route path="/tenant/license" element={<TenantLicensePage />} />
            <Route path="/tenant/oidc" element={<OidcConfigPage />} />
            <Route path="/tenant/team" element={<TeamPage />} />
            <Route path="/tenant/settings" element={<SettingsPage />} />

            {/* Default redirect — vendor goes to /vendor/tenants, customer to /tenant */}
            <Route index element={<LandingRedirect />} />
          </Route>
        </Route>
      </Route>
    </Routes>
  );
}
