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

@Injectable({ providedIn: 'root' })
export class RedirectCruscottiGuard {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {}

  canActivate(): Observable<boolean> | boolean {
    return this.authService.currentUser.pipe(
      map((user: AccountResDto | null) => {
        if (!user || !user.privileges) {
          return false;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('PRESTAZIONI_RIMBORSI')
        ) {
          this.router.navigate(['/cruscotti', 'prestazioni-rimborsi']);
          return true;
        } else {
          return false;
        }
      }),
    );
  }
}
