/**
 * CheckApiHealthUseCase
 * 
 * Executes health checks and returns status.
 * This Use Case orchestrates the health check process and emits events.
 */

import { HealthCheckQuery, HealthCheckResult } from '../ports/HealthCheckQuery';
import { HealthEventPublisher } from '../ports/HealthEventPublisher';

export interface CheckApiHealthUseCasePorts {
  healthCheckAdapter: HealthCheckQuery;
  eventPublisher: HealthEventPublisher;
}

export class CheckApiHealthUseCase {
  constructor(private readonly ports: CheckApiHealthUseCasePorts) {}

  /**
   * Execute a health check
   */
  async execute(): Promise<HealthCheckResult> {
    const { healthCheckAdapter, eventPublisher } = this.ports;

    try {
      // Perform the health check
      const result = await healthCheckAdapter.performHealthCheck();

      // Emit appropriate event based on result
      if (result.healthy) {
        await eventPublisher.publishHealthCheckCompleted({
          healthy: result.healthy,
          responseTime: result.responseTime,
          timestamp: result.timestamp,
        });
      } else {
        await eventPublisher.publishHealthCheckFailed({
          error: result.error || 'Unknown error',
          timestamp: result.timestamp,
        });
      }

      return result;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      const timestamp = new Date();

      // Emit failed event
      await eventPublisher.publishHealthCheckFailed({
        error: errorMessage,
        timestamp,
      });

      return {
        healthy: false,
        responseTime: 0,
        error: errorMessage,
        timestamp,
      };
    }
  }
}
