import { Injectable } from "@angular/core";
import { Account } from "../models/Account";
import { BehaviorSubject, firstValueFrom } from "rxjs";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";

@Injectable({ providedIn: 'root' })
export class Authentication{

    private _user = new BehaviorSubject<Account>( new Account );
    user$ = this._user.asObservable();

    constructor( private http: HttpClient){ }

    async loadLoginState(): Promise<void> {
        try {
            this._user.next( await firstValueFrom(this.http.post<Account>( "api/account/loginState", {}, {} )) );
        } catch (err: unknown){
            if (err instanceof HttpErrorResponse) {
                console.error( err.error );
            }
        }
    }

    Logout(){
        this._user.next( new Account );
        return this.http.post<Account>( "api/account/logout", {}, { responseType: 'json' } );
    }

    get isLoggedIn(): boolean {
        return this._user.value.id != null ? true : false;
    }

    get loggedInUser(): Account {
        return this._user.value;
    }
}