// Simple in-memory cache for API responses
const cache = new Map();
const CACHE_DURATION = 30000; // 30 seconds (reduced from 60)

export const getCached = (key) => {
  const cached = cache.get(key);
  if (!cached) return null;

  const isExpired = Date.now() - cached.timestamp > CACHE_DURATION;
  if (isExpired) {
    cache.delete(key);
    return null;
  }

  return cached.data;
};

export const setCache = (key, data) => {
  cache.set(key, {
    data,
    timestamp: Date.now(),
  });
};

export const clearCache = (key) => {
  if (key) {
    // If key ends with a dash, clear all keys starting with that prefix
    if (key.endsWith("-")) {
      const prefix = key;
      const keysToDelete = [];
      for (const [cacheKey] of cache) {
        if (cacheKey.startsWith(prefix)) {
          keysToDelete.push(cacheKey);
        }
      }
      keysToDelete.forEach((k) => cache.delete(k));
    } else {
      cache.delete(key);
    }
  } else {
    cache.clear();
  }
};

// Debounce function for API calls
export const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};
