import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ModalService } from '../modal/modal.service';

@Injectable({
  providedIn: 'root',
})
export class LocalStorageService {
  private readonly AUTH_TOKEN_KEY = 'auth_token';
  private readonly USERNAME_KEY = 'username';

  constructor(private router: Router, private modalService: ModalService) {}

  setToken(token: string): void {
    localStorage.setItem(this.AUTH_TOKEN_KEY, token);
  }

  setUsername(username: string): void {
    localStorage.setItem(this.USERNAME_KEY, username);
  }

  getUsername(): string | null{
    return localStorage.getItem(this.USERNAME_KEY);
  }

  removeUsername(): void {
    localStorage.removeItem(this.USERNAME_KEY);
  }

  getToken(): string | null {
    // Check if token is expired
    const token = localStorage.getItem(this.AUTH_TOKEN_KEY);
    if (token) {
      const payload = JSON.parse(atob(token.split('.')[1]));
      const expirationDate = new Date(payload.exp * 1000);
      if (expirationDate < new Date()) {
        this.removeToken(); // Remove expired token
        this.router.navigate(['/']).then(() => {
          this.modalService.openModal('login-modal');
        });
        return null;
      }
    }
    return localStorage.getItem(this.AUTH_TOKEN_KEY);
  }

  removeToken(): void {
    localStorage.removeItem(this.AUTH_TOKEN_KEY);
  }
}
