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 RedirectGuard {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {}

  canActivate(): Observable<boolean> | boolean {
    return this.authService.currentUser.pipe(
      map((user: AccountResDto | null) => {
        if (!user || !user.privileges) {
          this.router.navigate(['/public/strutture']);
          return true;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('DASHBOARD')
        ) {
          this.router.navigate(['dashboard']);
          return true;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('ACCOUNT_MANAGER')
        ) {
          this.router.navigate(['/utenti']);
          return true;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('WELLFARE')
        ) {
          this.router.navigate(['/report/wellfare']);
          return true;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('ROLE_MANAGER')
        ) {
          this.router.navigate(['/ruoli']);
          return true;
        } else if (
          user &&
          user.privileges &&
          user.privileges
            .map((privilege) => privilege.actionCode)
            .includes('STRUTTURE')
        ) {
          this.router.navigate(['/strutture']);
          return true;
        } else {
          return false;
        }
      }),
    );
  }
}
