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

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

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    return this.authenticationService.isLoggedIn$.pipe(
      switchMap(loggedIn => {
        if (loggedIn) {
          return this.authenticationService.isTokenValid$.pipe(
            switchMap(({ isValid, isRefreshable }) => {
              if (isValid) {
                return of(true);
              }
              if (isRefreshable) {
                return this.authenticationService.refreshToken$();
              }
              this.redirectToLoginPage();
              return of(false);
            })
          );
        } 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();

    if (environment.ciam.clientId) {
      document.location.href = `${environment.ciam.loginUrl}&client_id=${environment.ciam.clientId}&redirect_uri=${window.location.origin}`;
    } else {
      void this.router.navigateByUrl(environment.ciam.loginUrl);
    }
  }
}
