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 RedirectJobsGuard {
  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('CHIUSURE_AUTOMATICHE')
        ) {
          this.router.navigate(['/jobs', 'chiusure-automatiche']);
          return true;
        } else {
          return false;
        }
      }),
    );
  }
}
