import { createClient } from 'redis';
import { config } from '../index';
import { logger } from '../../utils/logger';

class RedisConnection {
  private client: ReturnType<typeof createClient> | null = null;

  async connect() {
    try {
      this.client = createClient({
        url: config.redis.url
      });

      this.client.on('error', (error) => {
        logger.error('Redis连接错误:', error);
      });

      this.client.on('connect', () => {
        logger.log('Redis连接成功');
      });

      this.client.on('end', () => {
        logger.log('Redis连接已关闭');
      });

      await this.client.connect();
    } catch (error) {
      logger.error('Redis连接失败:', error);
      throw error;
    }
  }

  async getClient() {
    if (!this.client || !this.client.isReady) {
      await this.connect();
    }
    return this.client!;
  }

  async get(key: string) {
    const client = await this.getClient();
    return client.get(key);
  }

  async set(key: string, value: string | number | Buffer, options?: {
    ex?: number;
    px?: number;
    nx?: boolean;
    xx?: boolean;
  }) {
    const client = await this.getClient();
    const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
    if (options) {
      // 使用Redis v4的正确set方法参数格式
      const setOptions: any = {};
      if (options.ex) setOptions.EX = options.ex;
      if (options.px) setOptions.PX = options.px;
      if (options.nx) setOptions.NX = options.nx;
      if (options.xx) setOptions.XX = options.xx;
      return client.set(key, stringValue, setOptions);
    } else {
      return client.set(key, stringValue);
    }
  }

  async del(key: string) {
    const client = await this.getClient();
    return client.del(key);
  }

  async exists(key: string) {
    const client = await this.getClient();
    return client.exists(key);
  }

  async close() {
    if (this.client) {
      await this.client.quit();
      logger.log('Redis连接已关闭');
    }
  }
}

export const redisConnection = new RedisConnection();