<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Monitoring;

use Prometheus\CollectorRegistry;
use Prometheus\Gauge;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;

/**
 * Collects Messenger queue metrics for Prometheus.
 *
 * Exposes a gauge for the number of messages waiting in the async transport.
 * Uses the RabbitMQ management API to query queue depth.
 */
final class MessengerMetricsCollector implements MessengerMetricsCollectorInterface
{
    private const string NAMESPACE = 'classeo';

    private Gauge $messagesWaiting;

    public function __construct(
        private readonly CollectorRegistry $registry,
        private readonly HttpClientInterface $httpClient,
        private readonly string $rabbitmqManagementUrl = 'http://rabbitmq:15672',
        private readonly string $rabbitmqUser = 'guest',
        private readonly string $rabbitmqPassword = 'guest',
    ) {
        $this->messagesWaiting = $this->registry->getOrRegisterGauge(
            self::NAMESPACE,
            'messenger_messages_waiting',
            'Number of messages waiting in transport queue',
            ['transport'],
        );
    }

    public function collect(): void
    {
        try {
            $response = $this->httpClient->request(
                'GET',
                $this->rabbitmqManagementUrl . '/api/queues/%2f/messages',
                [
                    'auth_basic' => [$this->rabbitmqUser, $this->rabbitmqPassword],
                    'timeout' => 2,
                ],
            );

            if ($response->getStatusCode() === 200) {
                $data = $response->toArray();
                $messageCount = $data['messages'] ?? 0;
                $this->messagesWaiting->set((float) $messageCount, ['async']);
            }
        } catch (Throwable) {
            // If RabbitMQ management API is unavailable, skip metric update
        }
    }
}
