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 of(true);
        } else if (route.queryParams.code) {
          return this.authenticationService.login$(route.queryParams.code).pipe(map(result => !!result));
        }

        void this.authenticationService.removeLocalStorageData();

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