const fs = require('fs');
const path = require('path');

const dbPath = path.resolve(__dirname, 'cache.json');

// Initialize cache file
if (!fs.existsSync(dbPath)) {
  fs.writeFileSync(dbPath, JSON.stringify({}), 'utf-8');
}

const readCache = () => {
  try {
    const data = fs.readFileSync(dbPath, 'utf-8');
    return JSON.parse(data);
  } catch (e) {
    return {};
  }
};

const writeCache = (data) => {
  try {
    fs.writeFileSync(dbPath, JSON.stringify(data), 'utf-8');
  } catch (e) {
    console.error('Failed to write cache', e);
  }
};

const getCache = (key, ttlMs) => {
  const cache = readCache();
  const row = cache[key];
  if (!row) return null;
  const now = Date.now();
  if (now - row.timestamp > ttlMs) {
    // Cache expired
    delete cache[key];
    writeCache(cache);
    return null;
  }
  return row.data;
};

const setCache = (key, data) => {
  const cache = readCache();
  cache[key] = {
    data: data,
    timestamp: Date.now()
  };
  writeCache(cache);
};

const clearCache = () => {
  writeCache({});
};

module.exports = { getCache, setCache, clearCache };
