// composables/useApiCache.js
export const useApiCache = () => {
  // داده‌های ذخیره شده (key -> response data)
  const cacheData = useState("cacheData", () => ({}));

  // درخواست‌های در حال اجرا (key -> Promise)
  const pendingRequests = useState("pendingRequests", () => ({}));

  // زمان انقضا برای هر key (ms)
  const ttlMap = useState("ttlMap", () => ({}));

  // ---- متدهای ساده و قابل فهم ----
  const hasData = (key) => key in cacheData.value;
  const getData = (key) => cacheData.value[key];
  const saveData = (key, data) => (cacheData.value[key] = data);
  const removeData = (key) => {
    delete cacheData.value[key];
    delete ttlMap.value[key];
  };
  const clearAllData = () => {
    Object.keys(cacheData.value).forEach((k) => delete cacheData.value[k]);
    Object.keys(pendingRequests.value).forEach(
      (k) => delete pendingRequests.value[k],
    );
    Object.keys(ttlMap.value).forEach((k) => delete ttlMap.value[k]);
  };

  const getPending = (key) => pendingRequests.value[key];
  const setPending = (key, promise) => (pendingRequests.value[key] = promise);
  const clearPending = (key) => delete pendingRequests.value[key];

  const saveDataWithTTL = (key, data, ttlSeconds = 0) => {
    saveData(key, data);
    if (ttlSeconds > 0) {
      ttlMap.value[key] = Date.now() + ttlSeconds * 1000;
    } else {
      delete ttlMap.value[key];
    }
  };

  const isExpired = (key) => {
    const expireTime = ttlMap.value[key];
    if (!expireTime) return false;
    return Date.now() > expireTime;
  };

  return {
    hasData,
    getData,
    saveData,
    removeData,
    clearAllData,
    getPending,
    setPending,
    clearPending,
    saveDataWithTTL,
    isExpired,
  };
};
