import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, 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({ providedIn: 'root' })
export class PrivilegeGuard implements CanActivate {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | boolean {
    const expectedPrivileges = route.data[
      'expectedPrivileges'
    ] as Array<string>;

    return this.authService.currentUser.pipe(
      map((user: AccountResDto | null) => {
        if (!user || !user['privileges']) {
          this.router.navigate(['/login']);
          return false;
        }
        const userPrivileges = user.privileges.map(
          (privilege) => privilege.actionCode,
        ); // se invio expectedVisibleLevels mappo solo quelli che hanno quel level
        if (
          !isEmpty(intersection(expectedPrivileges, userPrivileges)) &&
          intersection(expectedPrivileges, userPrivileges).length ===
            expectedPrivileges.length
        ) {
          // deve avere tutti i privilegi richiesti da expectedPrivileges
          return true;
        } else {
          this.router.navigate(['']);
          return false;
        }
      }),
    );
  }
}
