import {Injectable} from '@angular/core';
import {MastodonApiAuthenticationService} from "../../../../../mastodon-api/src/lib/services/mastodon-api-authentication.service";
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router";
import {map, Observable, tap} from "rxjs";
import {PersistentStore} from "../state/persistent/persistent-store.service";
import {Store} from "@ngrx/store";

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

    constructor(private persistentStore: PersistentStore,
                private store: Store,
                private router: Router,
                private mastodonApiAuthService: MastodonApiAuthenticationService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
        const currentInstance = this.persistentStore.value.currentInstance;
        if (currentInstance && currentInstance.accessToken && currentInstance.accountId) return true;
        if (currentInstance && currentInstance.accessToken && !currentInstance.accountId) {
            return this.mastodonApiAuthService.verifyCredentials(currentInstance.instanceName, currentInstance.accessToken).pipe(
                map((accountId) => {
                    this.persistentStore.set(
                        'currentInstance',
                        {...currentInstance, 'accountId': accountId}
                    );
                    return !!accountId;
                })
            );
        }
        this.router.navigate(['/auth']);
        return false;
    }
}
