import {Injectable} from '@angular/core';
import {CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {DefaultAuthService} from './default-auth.service';
import {PAIAAuthService} from './paia/paia-auth.service';
import {IAuthService} from 'ionic-appauth';
import {ActivatedAuthRouteSnapshot} from './auth-routes';

@Injectable({
  providedIn: 'root',
})
export class AuthGuardService implements CanActivate {
  authService: IAuthService | PAIAAuthService;

  constructor(
    private defaultAuth: DefaultAuthService,
    private paiaAuth: PAIAAuthService,
    private router: Router,
  ) {}

  public async canActivate(
    route: ActivatedAuthRouteSnapshot,
    _state: RouterStateSnapshot,
  ) {
    switch (route.data.authProvider) {
      case 'paia':
        this.authService = this.paiaAuth;
        break;
      default:
        this.authService = this.defaultAuth;
        break;
    }

    try {
      await this.authService.getValidToken();
    } catch {
      this.router.navigate(['profile']);
      return false;
    }

    return true;
  }
}
