import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { Logger } from 'src/app/service/logger.service';
import { AuthService } from 'src/app/service/auth.service';

const logger = new Logger('AuthGuard');

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(
    private keycloak: KeycloakService,
    private auth: AuthService,
    private router: Router
  ) {}

  async canActivate(): Promise<boolean> {
    try {
      if (!this.keycloak.isLoggedIn()) {
        logger.debug('User not logged in, redirecting to login page');
        await this.auth.login();
      }

      if (this.keycloak.isTokenExpired()) {
        logger.debug('Token expired, updating token');
        await this.keycloak.updateToken();
      }
    } catch (err) {
      logger.error('Error during authentication', err);
      await this.router.navigate(['/']);
      return false;
    }

    logger.debug('Check is user logged in');
    return this.keycloak.isLoggedIn();
  }
}
