import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router";
import {Observable, tap} from "rxjs";
import {select, Store} from "@ngrx/store";
import {selectIsLoggedIn} from "../../shared/state/store";

@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {

    constructor(private store: Store, private router: Router) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        return this.store
            .pipe(
                select(selectIsLoggedIn),
                tap((isLoggedIn) => {
                    if (!isLoggedIn) {
                        this.router.navigate(['/authorize']);
                    }
                }),
            );
    }
}
