import axios from "axios";
import Cookies from "js-cookie";

// utility to get data with caching
export async function fetchDataWithCache(endpoint:string) {
    const cacheKey = `cache_${endpoint}`;
    const cached = localStorage.getItem(cacheKey);

    const authToken = Cookies.get("jazz_token");

    const axiosInstance = axios.create({
      baseURL: "https://api.jazzagain.com/public/index.php",
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    });
  
    if (cached) {
      const { data, timestamp } = JSON.parse(cached);
      const isFresh = Date.now() - timestamp < 120000;
  
      if (isFresh) {
        return data;
      }
    }
  
    // If data is not in cache or is stale, fetch from API
    try {
      const response = await axiosInstance.get(endpoint);
      const data = response;
      console.log(response)
  
      // Cache the new data along with the current timestamp
      localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: Date.now() }));
      return data;
    } catch (error) {
      throw error;
    }
  }