import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { AccountResDto } from '@api/models';
import { AuthService } from '@core/services/auth.service';
import { intersection, isEmpty } from 'lodash';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class RoleGuard {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | boolean {
    const expectedRoles = route.data['expectedRoles'];
    return this.authService.currentUser.pipe(
      map((user: AccountResDto | null) => {
        if (!user || !user['roles']) {
          this.router.navigate(['']);
          return false;
        }
        const userRoles = user.roles.map((role) => role.roleCode);
        if (!isEmpty(intersection(expectedRoles, userRoles))) {
          return true;
        } else {
          this.router.navigate(['']);
          return false;
        }
      }),
    );
  }
}
