import type { ReactNode } from 'react';
import { Suspense } from 'react';
import { useLocation } from 'react-router-dom';
import { useShellOutletContext } from '@/app/shellOutletContext';
import { PageSkeleton } from '@/components/ui/page-skeleton';
import { canUserRoleAccessModuleRoute } from '@/shared/constants/moduleRoutes';
import NotFound from '@/pages/NotFound';

interface ModuleRouteGuardProps {
  readonly children: ReactNode;
}

export function ModuleRouteGuard({ children }: ModuleRouteGuardProps) {
  const location = useLocation();
  const shell = useShellOutletContext();

  // Forbidden direct-URL access lands on the 404 page (not a silent redirect).
  if (!canUserRoleAccessModuleRoute(location.pathname, shell.userRole)) {
    return <NotFound />;
  }

  return (
    <Suspense fallback={<PageSkeleton />}>
      {children}
    </Suspense>
  );
}
