import type { ReactNode } from 'react';
import { Suspense } from 'react';
import { useLocation } from 'react-router-dom';
import { useShellOutletContext } from '@/app/shellOutletContext';
import { canAccessScopedModuleRoute } from '@/business/app-shell/selectors';
import { PageSkeleton } from '@/components/ui/page-skeleton';
import { useScopeContext } from '@/contexts/scope-context';
import { MODULES } from '@/shared/constants/appData';
import NotFound from '@/pages/NotFound';

interface ModuleRouteGuardProps {
  readonly children: ReactNode;
}

export function ModuleRouteGuard({ children }: ModuleRouteGuardProps) {
  const location = useLocation();
  const shell = useShellOutletContext();
  const { tier, selectedTenant } = useScopeContext();
  const effectiveTier = selectedTenant ? selectedTenant.level : tier;
  const isDrilled = selectedTenant !== null;

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

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