import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Router } from '@angular/router';
import { BehaviorSubject, catchError, filter, Observable, switchMap, tap, throwError } from 'rxjs';
import { TokenService } from './token.service';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  authState: any;
  apiBaseUrl = "/auth";

  constructor(private router: Router, private http: HttpClient, private tokenService: TokenService) {
  }

  refreshToken(token: string) {
    return this.http.post<any>(this.apiBaseUrl + "/refresh-token", {
      "refreshToken": token
    }).pipe(
      tap(response => {
        this.tokenService.saveToken(response.accessToken);
        this.tokenService.saveRefreshToken(response.refreshToken);
      })
    );
  }

  get isUserAnonymousLoggedIn(): boolean {
    return this.authState !== null ? this.authState.isAnonymous : false;
  }

  get currentUserId(): string {
    return this.authState !== null ? this.authState.uid : '';
  }

  get currentUserName(): string {
    return this.authState['email'];
  }

  get currentUser(): any {
    return this.authState !== null ? this.authState : null;
  }

  get isUserEmailLoggedIn(): boolean {
    if (this.authState !== null && !this.isUserAnonymousLoggedIn) {
      return true;
    } else {
      return false;
    }
  }

  loginWithUserPass(username: string, password: string): Observable<{ accessToken: string, refreshToken: string }> {
    const body = {
      username: username,
      password: password
    }
    return this.http.post<{ accessToken: string, refreshToken: string }>(this.apiBaseUrl + "/login", body)
  }

  logout() {
    sessionStorage.clear()
    localStorage.clear()
    this.router.navigate(['/auth/login']);
  }

}
