using NATS.Server.JetStream.Storage;

namespace NATS.Server.JetStream.Tests;

public class FileStoreTests
{
    [Fact]
    public async Task FileStore_recovers_messages_after_restart()
    {
        var dir = Directory.CreateTempSubdirectory();

        await using (var store = new FileStore(new FileStoreOptions { Directory = dir.FullName }))
            await store.AppendAsync("foo", "payload"u8.ToArray(), default);

        await using var recovered = new FileStore(new FileStoreOptions { Directory = dir.FullName });
        (await recovered.GetStateAsync(default)).Messages.ShouldBe((ulong)1);
    }

    [Fact]
    public async Task Snapshot_round_trip_preserves_headers_and_payload_separately()
    {
        var srcDir = Directory.CreateTempSubdirectory();
        var dstDir = Directory.CreateTempSubdirectory();

        await using var src = new FileStore(new FileStoreOptions { Directory = srcDir.FullName });
        var hdr = "NATS/1.0\r\nX-Test: two\r\n\r\n"u8.ToArray();
        var msg = "payload-two"u8.ToArray();

        var (seq, _) = src.StoreMsg("events.a", hdr, msg, 0L);
        var snapshot = await src.CreateSnapshotAsync(default);

        await using var dst = new FileStore(new FileStoreOptions { Directory = dstDir.FullName });
        await dst.RestoreSnapshotAsync(snapshot, default);

        var loaded = dst.LoadMsg(seq, null);
        loaded.Header.ShouldNotBeNull();
        loaded.Header.ShouldBe(hdr);
        loaded.Data.ShouldNotBeNull();
        loaded.Data.ShouldBe(msg);
    }
}
