import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router';
import { AuthenticationService } from '@msfa-services/api/authentication.service';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private authenticationService: AuthenticationService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    const isLoggedIn = this.authenticationService.isLoggedIn;
    const isTokenValid = this.authenticationService.isTokenValid;
    const isTokenRefreshable = this.authenticationService.isTokenRefreshable;

    if (isLoggedIn) {
      if (isTokenValid) {
        return of(true);
      }
      if (isTokenRefreshable) {
        return this.authenticationService.refreshToken$();
      }
    } else if (route.queryParams.code) {
      return this.authenticationService.login$(route.queryParams.code).pipe(map(result => !!result));
    }

    this.redirectToLoginPage();
    return of(false);
  }

  redirectToLoginPage(): void {
    this.authenticationService.removeLocalStorageData();
    void this.router.navigateByUrl('/logga-in');
  }
}
