using NATS.Server.JetStream.Storage;

namespace NATS.Server.JetStream.Tests;

public class JetStreamStoreIndexTests
{
    [Fact]
    public async Task Store_can_get_last_message_by_subject()
    {
        var store = new MemStore();
        await store.AppendAsync("orders.created", "1"u8.ToArray(), default);
        await store.AppendAsync("orders.updated", "2"u8.ToArray(), default);
        await store.AppendAsync("orders.created", "3"u8.ToArray(), default);

        var last = await store.LoadLastBySubjectAsync("orders.created", default);
        last!.Payload.Span.SequenceEqual("3"u8).ShouldBeTrue();
    }

    [Fact]
    public async Task FileStore_trim_to_zero_preserves_high_water_mark_for_empty_state()
    {
        var dir = Directory.CreateTempSubdirectory();
        await using var store = new FileStore(new FileStoreOptions { Directory = dir.FullName });

        await store.AppendAsync("orders.created", "1"u8.ToArray(), default);
        await store.AppendAsync("orders.updated", "2"u8.ToArray(), default);
        await store.AppendAsync("orders.created", "3"u8.ToArray(), default);

        store.TrimToMaxMessages(0);

        var state = await store.GetStateAsync(default);
        state.Messages.ShouldBe(0UL);
        state.LastSeq.ShouldBe(3UL);
        state.FirstSeq.ShouldBe(4UL);
    }
}
