import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router';
import { RoleEnum } from '@msfa-enums/role.enum';
import { UserService } from '@msfa-services/api/user.service';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';

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

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    const expectedRole: RoleEnum = route.data.expectedRole as RoleEnum;

    return this.userService.userRoles$.pipe(
      filter(roles => !!roles),
      map(roles => {
        const userHasRole = roles.some(role => role.type === expectedRole);

        if (userHasRole) {
          return true;
        }

        void this.router.navigateByUrl('/obehorig');
      })
    );
  }
}
