import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import LZString from 'lz-string';

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

  constructor(private httpClient: HttpClient) { }

  /**
   * Fetches data from the cache or API based on the cache's age.
   * @param key The localStorage key to save the fetched data.
   * @param apiUrl The API URL to fetch the data from.
   * @param maxAgeMinutes The maximum age of the cached data in minutes.
   */
  fetchData<T>(key: string, apiUrl: string, maxAgeMinutes: number = 15): Observable<T> {
    const storedData = localStorage.getItem(key);
    const storedDate = localStorage.getItem(`${key}_lastFetchDate`);
    const now = new Date();

    if (storedData && storedDate) {
      const lastFetchDate = new Date(storedDate);
      const diffMinutes = Math.floor(((now.getTime() - lastFetchDate.getTime()) / 1000) / 60);

      if (diffMinutes < maxAgeMinutes) {
        // If data is less than maxAgeMinutes old, parse and return it as an Observable
        return of(JSON.parse(LZString.decompressFromUTF16(storedData)));
      }
    }

    // If no data in storage or data is older than maxAgeMinutes, fetch from API
    return this.httpClient.get<T>(apiUrl).pipe(
      tap(response => {
        // Save the new data and current date to local storage
        localStorage.setItem(key, LZString.compressToUTF16(JSON.stringify(response)));
        localStorage.setItem(`${key}_lastFetchDate`, new Date().toISOString());
      })
    );
  }
}
