import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { Logger } from 'src/app/service/logger.service';
import { ToastService } from 'src/app/service/toast.service';
import { AuthService } from 'src/app/service/auth.service';
import { PermissionsEnum } from 'src/app/model/auth/permissionsEnum';
import { SidebarService } from 'src/app/service/sidebar.service';

const log = new Logger('PermissionGuard');

@Injectable({
  providedIn: 'root',
})
export class PermissionGuard {
  constructor(
    private router: Router,
    private toast: ToastService,
    private auth: AuthService,
    private sidebar: SidebarService
  ) {}

  async canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
    const permissions = route.data['permissions'] as PermissionsEnum[];
    const isInUserSpace = route.data['isInUserSpace'] as boolean;

    if (isInUserSpace) {
      return (
        this.sidebar.selectedUserSpace$.value !== undefined &&
        this.sidebar.selectedUserSpace$.value !== null
      );
    }

    if (!permissions || permissions.length === 0) {
      return true;
    }

    const validate = await this.auth.hasAnyPermissionLazy(permissions);
    if (!validate) {
      log.debug('Permission denied', permissions);
      this.toast.warn('common.warning', 'error.permission_denied');
      this.router.navigate(['/']).then();
    }
    log.debug('Permission granted', permissions);
    return validate;
  }
}
