<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Monitoring\External;

use CpCreation\VitiCore\Monitoring\External\Message\DeliverExternalConnectionHealthMessage;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Contracts\Service\ResetInterface;

final class ExternalConnectionHealthReporter implements ResetInterface
{
    /** @var array<string, bool> */
    private array $reportedStates = [];

    public function __construct(
        private readonly MessageBusInterface $messageBus,
    ) {}

    public function report(string $service, bool $healthy, int $latencyMs, ?string $error = null): void
    {
        $service = mb_substr(mb_strtolower(mb_trim($service)), 0, 64);
        if (($this->reportedStates[$service] ?? null) === $healthy) {
            return;
        }
        $this->reportedStates[$service] = $healthy;

        $this->messageBus->dispatch(new DeliverExternalConnectionHealthMessage([
            'event_id' => Uuid::uuid7()->toString(),
            'service' => $service,
            'healthy' => $healthy,
            'latency_ms' => max(0, min(300_000, $latencyMs)),
            'error' => null === $error ? null : mb_substr(mb_trim($error), 0, 2000),
            'checked_at' => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(\DATE_ATOM),
        ]));
    }

    public function reset(): void
    {
        $this->reportedStates = [];
    }
}
