import { Injectable } from "@angular/core";
import { CanActivate } from "@angular/router";
import { KeycloakService } from "keycloak-angular";

@Injectable({
  providedIn: "root",
})
export class AuthGuard implements CanActivate {
  constructor(private keycloak: KeycloakService) {}

  async canActivate(): Promise<boolean> {
    if (this.keycloak.isTokenExpired()) {
      await this.keycloak.updateToken();
    }

    if (!this.keycloak.isLoggedIn()) {
      await this.keycloak.login();
    }

    return this.keycloak.isLoggedIn();
  }
}
