import {Injectable} from '@angular/core';
import {Author} from './models/author';
import {BehaviorSubject} from 'rxjs';
import {DateTime} from 'luxon';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private sessionExpiredSubject = new BehaviorSubject<boolean>(false);
  sessionExpired$ = this.sessionExpiredSubject.asObservable();

  constructor() {
    this.checkSessionExpiration();
  }

  isAuthenticated(): boolean {
    return sessionStorage.getItem("author") !== null &&
      sessionStorage.getItem("token") !== null &&
      sessionStorage.getItem("token-expiration-date") !== null;
  }

  getTokenExpirationDate(): string | null {
    return sessionStorage.getItem("token-expiration-date");
  }

  isSessionExpired(): boolean {
    const tokenExpirationDate = this.getTokenExpirationDate();
    if (tokenExpirationDate) {
      return DateTime.fromISO(tokenExpirationDate) < DateTime.now() && this.isAuthenticated();
    }
    return true
  }

  getAuthenticatedAuthor(): Author | null {
    const authorStr = sessionStorage.getItem('author')
    if (authorStr) {
      return JSON.parse(authorStr);
    }
    return null;
  }

  getAuthenticatedAuthorToken(): string | null{
    return sessionStorage.getItem('token');
  }

  setSessionExpired(expired: boolean) {
    this.sessionExpiredSubject.next(expired);
  }

  checkSessionExpiration() {
    if (this.isSessionExpired()) {
      this.setSessionExpired(true);
    }
  }
}
