import { Injectable, OnModuleDestroy, OnModuleInit, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Redis from 'ioredis';

@Injectable()
export class RedisService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(RedisService.name);
  private _client!: Redis;

  constructor(private readonly config: ConfigService) {}

  onModuleInit(): void {
    const url = this.config.getOrThrow<string>('redis.url');
    this._client = new Redis(url, { lazyConnect: false, maxRetriesPerRequest: 3 });
    this._client.on('error', (err) => this.logger.error(`Redis error: ${err.message}`));
    this._client.on('connect', () => this.logger.log('Redis connected'));
  }

  async onModuleDestroy(): Promise<void> {
    await this._client?.quit();
  }

  get client(): Redis {
    return this._client;
  }

  async setEx(key: string, value: string, ttlSeconds: number): Promise<void> {
    await this._client.set(key, value, 'EX', ttlSeconds);
  }

  async getDel(key: string): Promise<string | null> {
    const value = await this._client.get(key);
    if (value !== null) await this._client.del(key);
    return value;
  }

  async get(key: string): Promise<string | null> {
    return this._client.get(key);
  }

  async del(key: string): Promise<void> {
    await this._client.del(key);
  }
}
