import { Injectable } from '@nestjs/common';
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from '@nestjs/terminus';
import { ConfigService } from '@nestjs/config';
import Redis from 'ioredis';

@Injectable()
export class RedisHealthIndicator extends HealthIndicator {
  private redis: Redis;

  constructor(private configService: ConfigService) {
    super();
    const redisUrl = this.configService.get<string>('redis.url');
    this.redis = new Redis(redisUrl);
  }

  async isHealthy(key: string): Promise<HealthIndicatorResult> {
    try {
      const start = Date.now();
      await this.redis.ping();
      const responseTime = Date.now() - start;

      const result = this.getStatus(key, true, {
        responseTime: `${responseTime}ms`,
        status: 'up',
      });

      return result;
    } catch (error) {
      throw new HealthCheckError(
        'Redis health check failed',
        this.getStatus(key, false, {
          message: error.message,
          status: 'down',
        }),
      );
    }
  }

  onModuleDestroy() {
    this.redis.disconnect();
  }
}
