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/sign-in'], { 
      queryParams: { returnUrl: state.url } 
    });
    return false;
  }

  // Récupérer les rôles depuis le token
  const userRoles = authService.getCurrentUserRoles();
  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']);
    return false;
  }

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

// Fonction utilitaire pour extraire le chemin du module
function getModulePath(route: ActivatedRouteSnapshot): string {
  const segments: string[] = [];
  let currentRoute: ActivatedRouteSnapshot | null = route;
  
  while (currentRoute) {
    if (currentRoute.url.length > 0) {
      segments.unshift(...currentRoute.url.map(segment => segment.path));
    }
    currentRoute = currentRoute.firstChild;
  }
  
  return segments.join('/');
}