using System.Text;
using FluentAssertions;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

public static class DlqRoutingProbe
{
    public static async Task<bool> DlqTtlRoutesToEscalationQueueAsync(IOptions<RabbitMqOptions> opts)
    {
        var o = opts.Value;
        var factory = RabbitMqConnectionFactory.Create(o);

        using var connection = factory.CreateConnection("dlq-routing-probe");
        using var channel = connection.CreateModel();

        RabbitMqTestHelper.PurgeNotificationQueues(opts);

        var body = Encoding.UTF8.GetBytes(
            """{"alertId":"00000000-0000-0000-0000-000000000099","encounterId":"00000000-0000-0000-0000-000000000088"}""");

        channel.BasicPublish(
            exchange: "",
            routingKey: "alerts.paging.dlq",
            basicProperties: null,
            body: body);

        var dlqHasMessage = false;
        for (var i = 0; i < 20; i++)
        {
            await Task.Delay(250);
            var dlq = channel.QueueDeclarePassive("alerts.paging.dlq");
            if (dlq.MessageCount > 0)
            {
                dlqHasMessage = true;
                break;
            }
        }

        dlqHasMessage.Should().BeTrue("probe message should land in alerts.paging.dlq");

        var deadline = DateTimeOffset.UtcNow.AddSeconds(15);
        while (DateTimeOffset.UtcNow < deadline)
        {
            await Task.Delay(500);
            var dlq = channel.QueueDeclarePassive("alerts.paging.dlq");
            if (dlq.MessageCount == 0)
                return true;
        }

        return false;
    }
}
