const Redis = require('ioredis');
const config = require('../config');

class CacheService {
  constructor() {
    this.enabled = config.site.deployment === 'cloud' && config.site.redisHost
    this.client = null;
    
    if (this.enabled) {
      this.client = new Redis({
        host: config.site.redisHost,
        port: config.site.redisPort,
        password: config.site.redisPassword,
        tls: config.site.redisTLS ? {} : undefined,
      });
      
      this.client.on('error', (err) => {
        console.error('Redis Client Error', err);
      });
    }
  }

  async get(key) {
    if (!this.enabled) return null;
    
    try {
      const value = await this.client.get(key);
      return value ? JSON.parse(value) : null;
    } catch (error) {
      console.error('Cache get error:', error);
      return null;
    }
  }

  async set(key, value, ttlSeconds = 300) {
    if (!this.enabled) return;
    
    try {
      await this.client.setex(key, ttlSeconds, JSON.stringify(value));
    } catch (error) {
      console.error('Cache set error:', error);
    }
  }

  async del(key) {
    if (!this.enabled) return;
    
    try {
      await this.client.del(key);
    } catch (error) {
      console.error('Cache delete error:', error);
    }
  }
}

// Create a singleton instance
const cacheService = new CacheService();
module.exports = cacheService;