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

/**
 * Route guard for the configurable permission system. Reads
 * route.data['permission'] = { module, action } and blocks navigation if the
 * current user lacks it (redirecting to the dashboard). The parent route's
 * AuthGuard guarantees the session is restored before children activate.
 */
@Injectable({ providedIn: 'root' })
export class PermissionGuard implements CanActivate {
    constructor(
        private permissions: PermissionService,
        private auth: AuthService,
        private router: Router
    ) { }

    canActivate(route: ActivatedRouteSnapshot): boolean {
        const required = route.data['permission'] as PermissionRequirement | undefined;
        if (!required) {
            return true;
        }

        const allowed = this.permissions.can(required.module, required.action);
        if (!allowed) {
            this.router.navigate(['/user-portal/dashboard']);
        }
        return allowed;
    }
}
