import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '@/contexts/useAuth';
import { APP_ROUTE_PATHS } from '@/shared/constants/routes';
import { AppShellSkeleton } from '@/components/ui/app-shell-skeleton';

/**
 * Gate for the authenticated app shell (Workstream 3 §3.6). Once the session has
 * resolved, an unauthenticated visitor is redirected to `/login`; only the
 * public routes (`/login`, the error page) are reachable without a session.
 * While the session is still loading, keep the private shell unmounted. That
 * prevents module-level queries from firing before `/auth/me` confirms a
 * session.
 */
export function AuthGuard() {
  const { isAuthenticated, loading } = useAuth();

  if (loading) {
    return <AppShellSkeleton />;
  }

  if (!loading && !isAuthenticated) {
    return <Navigate to={APP_ROUTE_PATHS.login} replace />;
  }

  return <Outlet />;
}
