import { MODULES } from '@/shared/constants/appData';
import { APP_ROUTE_PATHS } from '@/shared/constants/routes';
import type { Module, ModuleId, UserRole } from '@/shared/types/app';

export const DEFAULT_MODULE_ID: ModuleId = 'dashboard';
export const DEFAULT_MODULE_ROUTE_PATH = APP_ROUTE_PATHS.dashboard;

function normalizeRoutePath(path: string): string {
  if (path.length > 1 && path.endsWith('/')) {
    return path.slice(0, -1);
  }

  return path;
}

export function getModuleById(moduleId: ModuleId): Module {
  return MODULES.find((module) => module.id === moduleId) ?? MODULES[0];
}

export function getModuleRoutePath(moduleId: ModuleId): string {
  return getModuleById(moduleId).routePath;
}

export function getModuleByRoutePath(pathname: string): Module | null {
  const normalizedPath = normalizeRoutePath(pathname);

  if (normalizedPath === APP_ROUTE_PATHS.home) {
    return getModuleById(DEFAULT_MODULE_ID);
  }

  return MODULES.find((module) => module.routePath === normalizedPath) ?? null;
}

export function getModuleIdByRoutePath(pathname: string): ModuleId {
  return getModuleByRoutePath(pathname)?.id ?? DEFAULT_MODULE_ID;
}

export function canUserRoleAccessModuleRoute(
  pathname: string,
  userRole: UserRole,
): boolean {
  const module = getModuleByRoutePath(pathname);

  return module ? module.roles.includes(userRole) : true;
}

/**
 * The landing route for a role: the first module the role can access (so e.g.
 * students/guardians land on a page they're allowed to see rather than the
 * dashboard, which they cannot access). Falls back to the dashboard.
 */
export function getDefaultRoutePathForRole(userRole: UserRole): string {
  const accessible = MODULES.find((module) => module.roles.includes(userRole));

  return accessible ? accessible.routePath : DEFAULT_MODULE_ROUTE_PATH;
}
