import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
import { AuthService } from '../../shared/services/auth.service';

@Injectable({ providedIn: 'root' })
export class RoleGuard implements CanActivate {
    constructor(
        private authService: AuthService,
        private router: Router
    ) { }

    canActivate(route: ActivatedRouteSnapshot): boolean {
        const requiredRoles = route.data['roles'] as string[] | undefined;
        if (!requiredRoles?.length) {
            return true;
        }

        const user = this.authService.getCurrentUser();
        const allowed = user?.roles?.some(r => requiredRoles.includes(r)) ?? false;

        if (!allowed) {
            this.router.navigate(['/user-portal/dashboard']);
        }

        return allowed;
    }
}
