<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Monitoring;

use Prometheus\CollectorRegistry;
use Prometheus\Gauge;

/**
 * Collects infrastructure health metrics for Prometheus.
 *
 * Exposes health_check_status gauge for each service (postgres, redis, rabbitmq).
 * Values: 1 = healthy, 0 = unhealthy
 *
 * These metrics are used by Grafana "Infrastructure Health" dashboard panels.
 *
 * @see Story 1.8 - T7: Health Check Endpoint
 */
final class HealthMetricsCollector implements HealthMetricsCollectorInterface
{
    private const string NAMESPACE = 'classeo';

    private Gauge $healthStatus;

    public function __construct(
        private readonly CollectorRegistry $registry,
        private readonly InfrastructureHealthCheckerInterface $healthChecker,
    ) {
        $this->healthStatus = $this->registry->getOrRegisterGauge(
            self::NAMESPACE,
            'health_check_status',
            'Health status of infrastructure services (1=healthy, 0=unhealthy)',
            ['service'],
        );
    }

    /**
     * Update all health metrics.
     *
     * Called before rendering metrics to ensure fresh health status.
     */
    public function collect(): void
    {
        $checks = $this->healthChecker->checkAll();

        foreach ($checks as $service => $isHealthy) {
            $this->healthStatus->set($isHealthy ? 1.0 : 0.0, [$service]);
        }
    }
}
