import { logger } from './logger';
import { recordSystemAlert, buildHealthAlertMessage } from './system-alerts';

type HealthStatus = 'healthy' | 'operational' | 'degraded' | 'unhealthy' | string;

/**
 * Send alert hooks for health endpoints (Sentry + logs).
 * Only fires when status is degraded/unhealthy to avoid noisy spam.
 */
export async function notifyHealthAlert(
  endpoint: string,
  status: HealthStatus,
  meta?: Record<string, unknown>
): Promise<void> {
  const normalized = String(status || '').toLowerCase();
  if (normalized === 'healthy' || normalized === 'operational') {
    return;
  }

  logger.warn('Health check alert triggered', {
    endpoint,
    status: normalized,
    ...meta,
  });

  await recordSystemAlert({
    title: 'Health check alert',
    message: buildHealthAlertMessage(endpoint, normalized, meta?.reason as string | undefined),
    severity: normalized === 'unhealthy' ? 'error' : 'warning',
    source: endpoint,
    environment: process.env.APP_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV,
    cooldownKey: `${endpoint}:${normalized}`,
    cooldownMinutes: 10,
  });

  if (!process.env.NEXT_PUBLIC_SENTRY_DSN) {
    return;
  }

  try {
    const sentryModuleName = '@sentry/nextjs';
    const Sentry = await import(/* webpackIgnore: true */ sentryModuleName) as {
      captureMessage: (message: string, options?: {
        level?: string;
        tags?: Record<string, string>;
        extra?: Record<string, unknown>;
      }) => void;
    };
    Sentry.captureMessage(`Health alert on ${endpoint}: ${normalized}`, {
      level: normalized === 'unhealthy' ? 'error' : 'warning',
      tags: {
        endpoint,
        status: normalized,
      },
      extra: meta,
    });
  } catch {
    // Sentry optional
  }
}
