using NATS.Server.JetStream;
using NATS.Server.JetStream.Models;

namespace NATS.Server.Tests;

public class JetStreamConsumerBackoffParityTests
{
    [Fact]
    public async Task Redelivery_honors_backoff_schedule_and_stops_after_max_deliver()
    {
        var streams = new StreamManager();
        streams.CreateOrUpdate(new StreamConfig
        {
            Name = "ORDERS",
            Subjects = ["orders.*"],
        });

        streams.Capture("orders.created", "x"u8.ToArray());

        var consumers = new ConsumerManager();
        consumers.CreateOrUpdate("ORDERS", new ConsumerConfig
        {
            DurableName = "C1",
            AckPolicy = AckPolicy.Explicit,
            AckWaitMs = 1,
            MaxDeliver = 3,
            BackOffMs = [1, 1],
        });

        var deliveries = new List<ulong>();
        for (var i = 0; i < 6; i++)
        {
            var batch = await consumers.FetchAsync("ORDERS", "C1", 1, streams, default);
            if (batch.Messages.Count > 0 && batch.Messages[0].Redelivered)
                deliveries.Add(batch.Messages[0].Sequence);
            await Task.Delay(2);
        }

        deliveries.Count.ShouldBe(3);
    }
}
