import {inject, Injectable} from '@angular/core';
import {DOCUMENT} from '@angular/common';

const TOKEN_KEY = 'auth-token';
const USER_KEY = 'auth-user';

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

  private document = inject<Document>(DOCUMENT);

  constructor() {

  }

  signOut(): void {
    this.document.defaultView?.sessionStorage.clear();
  }

  public saveToken(token: string): void {
    document.defaultView?.sessionStorage.removeItem(TOKEN_KEY);
    document.defaultView?.sessionStorage.setItem(TOKEN_KEY, token);
  }

  public getToken(): string | null| undefined {
    return document.defaultView?.sessionStorage.getItem(TOKEN_KEY);
  }

  public saveUser(user: any): void {
    document.defaultView?.sessionStorage.removeItem(USER_KEY);
    document.defaultView?.sessionStorage.setItem(USER_KEY, JSON.stringify(user));
  }

  public getUser(): any {
    const user = document.defaultView?.sessionStorage.getItem(USER_KEY);
    if (user) {
      return JSON.parse(user);
    }

    return {};
  }

  clean(): void {
    document.defaultView?.sessionStorage.clear();
  }

  public isLoggedIn(): boolean {
    const user = this.document.defaultView?.sessionStorage?.getItem(USER_KEY);
    if (user) {
      return true;
    }

    return false;
  }
}
