using NATS.Server.JetStream.Storage;

namespace NATS.Server.Tests.JetStream;

public class JetStreamFileStoreInvariantTests
{
    [Fact]
    public async Task Filestore_recovery_preserves_sequence_subject_index_and_integrity_after_prune_and_restart_cycles()
    {
        var dir = Path.Combine(Path.GetTempPath(), $"nats-js-fs-invariants-{Guid.NewGuid():N}");
        var options = new FileStoreOptions { Directory = dir };

        try
        {
            await using var store = new FileStore(options);
            var seq1 = await store.AppendAsync("orders.created", "1"u8.ToArray(), default);
            var seq2 = await store.AppendAsync("orders.updated", "2"u8.ToArray(), default);
            seq1.ShouldBe((ulong)1);
            seq2.ShouldBe((ulong)2);

            (await store.RemoveAsync(seq2, default)).ShouldBeTrue();
            var state = await store.GetStateAsync(default);

            state.Messages.ShouldBe((ulong)1);
            state.LastSeq.ShouldBe((ulong)1);
            state.FirstSeq.ShouldBe((ulong)1);
            (await store.LoadLastBySubjectAsync("orders.updated", default)).ShouldBeNull();
        }
        finally
        {
            if (Directory.Exists(dir))
                Directory.Delete(dir, recursive: true);
        }
    }
}
