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

@Injectable()
export class MongoHealthIndicator extends HealthIndicator {
  private client: MongoClient;

  constructor(private configService: ConfigService) {
    super();
    const uri = this.configService.get<string>('mongodb.uri');
    this.client = new MongoClient(uri);
  }

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

      return this.getStatus(key, true, {
        responseTime: `${responseTime}ms`,
        status: 'up',
      });
    } catch (error) {
      throw new HealthCheckError(
        'MongoDB health check failed',
        this.getStatus(key, false, {
          message: error.message,
          status: 'down',
        }),
      );
    } finally {
      await this.client.close();
    }
  }
}
