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

@Injectable()
export class AzureHealthIndicator extends HealthIndicator {
  private chatEndpoint: string;
  private chatApiKey: string;

  constructor(private configService: ConfigService) {
    super();
    this.chatEndpoint = this.configService.get<string>('ai.azure.chat.endpoint');
    this.chatApiKey = this.configService.get<string>('ai.azure.chat.apiKey');
  }

  async isHealthy(key: string): Promise<HealthIndicatorResult> {
    if (!this.chatEndpoint || !this.chatApiKey) {
      return this.getStatus(key, true, {
        status: 'skipped',
        message: 'Azure OpenAI not configured',
      });
    }

    try {
      const start = Date.now();

      // Simple health check: verify API key is valid
      // We don't send an actual request to avoid costs
      const url = `${this.chatEndpoint}/openai/deployments?api-version=2024-02-01`;

      await axios.get(url, {
        headers: {
          'api-key': this.chatApiKey,
        },
        timeout: 5000,
      });

      const responseTime = Date.now() - start;

      return this.getStatus(key, true, {
        responseTime: `${responseTime}ms`,
        status: 'up',
      });
    } catch (error) {
      // Don't fail health check if Azure is down - it's not critical for app startup
      // But log the error
      return this.getStatus(key, true, {
        status: 'degraded',
        message: error.message,
      });
    }
  }
}
