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

namespace NATS.Server.JetStream.Tests;

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

        streams.Capture("orders.a", "1"u8.ToArray());
        streams.Capture("orders.b", "2"u8.ToArray());
        streams.Capture("orders.a", "3"u8.ToArray());

        var consumers = new ConsumerManager();
        consumers.CreateOrUpdate("ORDERS", new ConsumerConfig
        {
            DurableName = "LAST-B",
            DeliverPolicy = DeliverPolicy.LastPerSubject,
            FilterSubject = "orders.b",
        }).Error.ShouldBeNull();

        var batch = await consumers.FetchAsync("ORDERS", "LAST-B", 1, streams, default);
        batch.Messages.Count.ShouldBe(1);
        batch.Messages[0].Subject.ShouldBe("orders.b");
        batch.Messages[0].Sequence.ShouldBe((ulong)2);
    }
}
