// app/core/auth/guards/role.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from 'app/core/auth/auth.service';
import { of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

export const RoleGuard: CanActivateFn = (route: ActivatedRouteSnapshot) => {
    const router: Router = inject(Router);
    const authService: AuthService = inject(AuthService);

    return authService.check().pipe(
        switchMap((authenticated) => {
            if (!authenticated) {
                // Not authenticated, redirect to sign-in
                console.log('User not authenticated, redirecting to sign-in');
                return of(router.parseUrl('/sign-in'));
            }

            // Get required roles from route data
            const requiredRoles = route.data['roles'] as string[];
            
            if (!requiredRoles || requiredRoles.length === 0) {
                // No role requirement, allow access
                console.log('No role requirement, allowing access');
                return of(true);
            }

            // Get user's role
            const userRole = authService.userRole;

            console.log('Role Guard Check:', {
                userRole,
                requiredRoles,
                path: route.routeConfig?.path
            });

            if (!userRole) {
                // No role assigned, redirect to dashboard
                console.warn('No role assigned to user, redirecting to dashboard');
                return of(router.parseUrl('/example'));
            }

            // Check if user has required role
            const hasRole = requiredRoles.includes(userRole);

            if (hasRole) {
                console.log(`Access granted for role: ${userRole}`);
                return of(true);
            } else {
                // User doesn't have required role, redirect based on their role
                console.warn(`Access denied. User role: ${userRole}, Required roles:`, requiredRoles);
                const redirectUrl = authService.getRoleBasedRedirectUrl();
                return of(router.parseUrl(redirectUrl));
            }
        })
    );
};