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";

const log = new Logger("PermissionGuard");

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

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

    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;
  }
}
