/**
 * Shared health check utilities for external services
 * Replaces duplicated checkServiceHealth() across modules
 */

import { fetchWithTimeout } from './fetch-with-timeout';

/**
 * Health check result interface
 */
export interface HealthCheckResult {
  online: boolean;
  error?: string;
}

/**
 * Shared health check utility for external services
 * Uses fetchWithTimeout to prevent hangs
 *
 * @param url - The service URL to check
 * @param timeoutMs - Timeout in milliseconds (default: 3000)
 * @returns HealthCheckResult with online status and optional error
 */
export async function checkServiceHealth(
  url: string,
  timeoutMs = 3000
): Promise<HealthCheckResult> {
  try {
    const response = await fetchWithTimeout(url, {}, timeoutMs);

    // Consider 2xx/3xx/4xx as "online", only 5xx as "offline"
    const online = response.ok || response.status < 500;
    return {
      online,
      error: online ? undefined : `HTTP ${response.status}`,
    };
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    return {
      online: false,
      error: message,
    };
  }
}

/**
 * Check multiple services in parallel
 * Useful for dashboard status checks
 *
 * @param services - Record of service name to URL mappings
 * @param timeoutMs - Timeout in milliseconds for each check (default: 3000)
 * @returns Record of service name to HealthCheckResult
 */
export async function checkServicesHealth(
  services: Record<string, string>,
  timeoutMs = 3000
): Promise<Record<string, HealthCheckResult>> {
  const results = await Promise.all(
    Object.entries(services).map(async ([name, url]) => {
      const result = await checkServiceHealth(url, timeoutMs);
      return [name, result] as const;
    })
  );

  return Object.fromEntries(results);
}

/**
 * Simplified boolean health check (backwards compatible)
 * Returns only online status without error details
 *
 * @param url - The service URL to check
 * @param timeoutMs - Timeout in milliseconds (default: 3000)
 * @returns boolean indicating if service is online
 */
export async function isServiceOnline(
  url: string,
  timeoutMs = 3000
): Promise<boolean> {
  const result = await checkServiceHealth(url, timeoutMs);
  return result.online;
}
