import { inject } from '@angular/core';
import { CanActivateFn, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { PermissionsService } from '../services/permissions.service';

export const roleGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state) => {
  const authService = inject(AuthService);
  const permissionsService = inject(PermissionsService);
  const router = inject(Router);

  // Vérifier d'abord l'authentification
  if (!authService.isAuthenticated()) {
    console.log('RoleGuard: User not authenticated, redirecting to login');
    router.navigate(['/auth/login'], { 
      queryParams: { 
        returnUrl: state.url,
        reason: 'not_authenticated'
      } 
    });
    return false;
  }

  // Récupérer les rôles depuis le token
  const userRoles = authService.getCurrentUserRoles();
  
  if (!userRoles || userRoles.length === 0) {
    console.warn('RoleGuard: User has no roles');
    router.navigate(['/unauthorized'], {
      queryParams: { reason: 'no_roles' }
    });
    return false;
  }

  const modulePath = getModulePath(route);
  
  console.log('🔐 RoleGuard check:', {
    module: modulePath,
    userRoles: userRoles,
    url: state.url
  });

  // Vérifier les permissions
  const hasAccess = permissionsService.canAccessModule(modulePath, userRoles);
  
  if (!hasAccess) {
    console.warn('❌ RoleGuard: Access denied for', modulePath, 'User roles:', userRoles);
    router.navigate(['/unauthorized'], {
      queryParams: { 
        module: modulePath,
        userRoles: userRoles.join(','),
        requiredRoles: getRequiredRolesForModule(permissionsService, modulePath).join(',')
      }
    });
    return false;
  }

  console.log('✅ RoleGuard: Access granted for', modulePath);
  return true;
};

// Fonction utilitaire pour extraire le chemin du module
function getModulePath(route: ActivatedRouteSnapshot): string {
  // Chercher le module dans les data de la route actuelle ou parente
  let currentRoute: ActivatedRouteSnapshot | null = route;
  
  while (currentRoute) {
    // Si le module est défini dans les data, l'utiliser
    if (currentRoute.data['module']) {
      return currentRoute.data['module'];
    }
    
    currentRoute = currentRoute.parent;
  }
  
  // Fallback: construire le chemin à partir des segments d'URL
  return buildPathFromUrl(route);
}

function buildPathFromUrl(route: ActivatedRouteSnapshot): string {
  const segments: string[] = [];
  let currentRoute: ActivatedRouteSnapshot | null = route;
  
  // Parcourir jusqu'à la racine
  while (currentRoute) {
    if (currentRoute.url.length > 0) {
      segments.unshift(...currentRoute.url.map(segment => segment.path));
    }
    currentRoute = currentRoute.parent;
  }
  
  return segments.join('/');
}

function getRequiredRolesForModule(permissionsService: PermissionsService, modulePath: string): string[] {
  // Cette fonction récupère les rôles requis pour un module donné
  // Vous devrez peut-être l'adapter selon votre implémentation PermissionsService
  const [mainModule] = modulePath.split('/');
  const permission = (permissionsService as any).findPermission?.(mainModule);
  return permission?.roles || [];
}