import { Injectable } from '@nestjs/common';
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from '@nestjs/terminus';
import { ConfigService } from '@nestjs/config';
import * as Minio from 'minio';

@Injectable()
export class MinioHealthIndicator extends HealthIndicator {
  private minioClient: Minio.Client;
  private bucket: string;

  constructor(private configService: ConfigService) {
    super();
    this.minioClient = new Minio.Client({
      endPoint: this.configService.get<string>('minio.endpoint'),
      port: this.configService.get<number>('minio.port'),
      useSSL: this.configService.get<boolean>('minio.useSSL', false),
      accessKey: this.configService.get<string>('minio.accessKey'),
      secretKey: this.configService.get<string>('minio.secretKey'),
    });
    this.bucket = this.configService.get<string>('minio.bucket');
  }

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

      if (!exists) {
        throw new Error(`Bucket ${this.bucket} does not exist`);
      }

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