const { LRUCache } = require('lru-cache');
const Redis = require('ioredis');

const localMemoryCache = new LRUCache({ max: 500, ttl: 1000 * 60 * 60 * 2 });
let redisClient = null;
if (process.env.REDIS_URL) {
  redisClient = new Redis(process.env.REDIS_URL, { lazyConnect: false, maxRetriesPerRequest: 1 });
  redisClient.on('error', (err) => console.warn('Redis License Cache Error:', err.message));
}

const KEY = (tenantId) => `license:tenant:${tenantId}`;

async function get(tenantId) {
  try {
    if (redisClient && redisClient.status === 'ready') {
      const raw = await redisClient.get(KEY(tenantId));
      if (raw) return JSON.parse(raw);
    }
  } catch (e) {
  }
  return localMemoryCache.get(KEY(tenantId)) || null;
}

async function set(tenantId, payload, ttlInSeconds) {
  const safeTtl = Math.max(ttlInSeconds, 60);
  try {
    if (redisClient && redisClient.status === 'ready') {
      await redisClient.set(KEY(tenantId), JSON.stringify(payload), 'EX', safeTtl);
    }
  } catch (e) {
  }
  localMemoryCache.set(KEY(tenantId), payload, { ttl: safeTtl * 1000 });
}

async function del(tenantId) {
  try {
    if (redisClient && redisClient.status === 'ready') await redisClient.del(KEY(tenantId));
  } catch (_) {
  }
  localMemoryCache.delete(KEY(tenantId));
}

module.exports = { get, set, del, _close: () => redisClient ? redisClient.quit() : Promise.resolve() };
