import type { ServiceHealth } from './types.js';
import type { Service } from '../services/types.js';

// Cache health check results to avoid overwhelming services
const healthCache = new Map<string, { health: ServiceHealth; timestamp: number }>();
const CACHE_TTL = 30000; // 30 seconds

export async function checkServiceHealth(service: Service): Promise<ServiceHealth> {
  const startTime = Date.now();
  let status: 'up' | 'down' | 'degraded' = 'down';

  // Check cache first
  const cached = healthCache.get(service.id);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.health;
  }

  try {
    const response = await fetch(service.healthUrl, {
      method: 'GET',
      signal: AbortSignal.timeout(10000), // 10 second timeout
      headers: {
        'User-Agent': 'ByteLyst-DevOps-HealthCheck/1.0',
      },
    });

    const responseTime = Date.now() - startTime;

    if (response.ok) {
      status = responseTime > 5000 ? 'degraded' : 'up';
    } else {
      status = 'down';
    }

    const health: ServiceHealth = {
      serviceId: service.id,
      status,
      responseTime,
      lastCheck: new Date().toISOString(),
    };

    // Cache the result
    healthCache.set(service.id, { health, timestamp: Date.now() });

    return health;
  } catch (error) {
    const health: ServiceHealth = {
      serviceId: service.id,
      status: 'down',
      lastCheck: new Date().toISOString(),
    };

    // Cache failures for shorter time (5 seconds)
    healthCache.set(service.id, { health, timestamp: Date.now() - CACHE_TTL + 5000 });

    return health;
  }
}

export async function checkAllServices(services: Service[]): Promise<ServiceHealth[]> {
  const healthChecks = await Promise.all(
    services.map(service => checkServiceHealth(service))
  );
  return healthChecks;
}

export function clearHealthCache(): void {
  healthCache.clear();
}
