import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { firstValueFrom, Observable } from 'rxjs';
import { AuthService } from './auth.service';

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

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return firstValueFrom(this.auth.guard())
      .then(res => Promise.resolve(true))
      .catch(err => {
        if (err.status == 401)
          return Promise.resolve(false)
        else return Promise.resolve(true);
      }).then(auth => {
        if (!auth)
          this.router.navigate(['/auth/login'], {
            queryParams: {
              return: state.url
            }
          });
        return auth;
      });
  }
}

