import { Navigate } from 'react-router-dom';
import { useShellOutletContext } from '@/app/shellOutletContext';
import { getScopedModules } from '@/business/app-shell/selectors';
import { useScopeContext } from '@/contexts/scope-context';
import { MODULES } from '@/shared/constants/appData';
import { DEFAULT_MODULE_ROUTE_PATH } from '@/shared/constants/moduleRoutes';

/**
 * Sends the index route (`/`) to the first module the current user can access.
 */
export function IndexRedirect() {
  const shell = useShellOutletContext();
  const { tier, selectedTenant } = useScopeContext();
  const effectiveTier = selectedTenant ? selectedTenant.level : tier;
  const scopedModules = getScopedModules(MODULES, shell.user, effectiveTier, selectedTenant !== null);
  const targetPath = scopedModules[0]?.routePath ?? DEFAULT_MODULE_ROUTE_PATH;

  return (
    <Navigate to={targetPath} replace />
  );
}
