using Microsoft.Extensions.Logging.Abstractions;
using NATS.Server.Configuration;

namespace NATS.Server.JetStream.Tests.JetStream;

public class JetStreamServerConfigParityBatch2Tests
{
    [Fact]
    public void JetStream_constants_match_go_default_values()
    {
        JetStreamOptions.JetStreamStoreDir.ShouldBe("jetstream");
        JetStreamOptions.JetStreamMaxStoreDefault.ShouldBe(1L << 40);
        JetStreamOptions.JetStreamMaxMemDefault.ShouldBe(256L * 1024 * 1024);
    }

    [Fact]
    public async Task Server_exposes_jetstream_enabled_config_and_store_dir()
    {
        var options = new NatsOptions
        {
            Host = "127.0.0.1",
            Port = 0,
            JetStream = new JetStreamOptions
            {
                StoreDir = Path.Combine(Path.GetTempPath(), "js-" + Guid.NewGuid().ToString("N")),
                MaxMemoryStore = 10_000,
                MaxFileStore = 20_000,
                MaxStreams = 7,
                MaxConsumers = 11,
                Domain = "D1",
            },
        };

        var server = new NatsServer(options, NullLoggerFactory.Instance);
        using var cts = new CancellationTokenSource();
        _ = server.StartAsync(cts.Token);
        await server.WaitForReadyAsync();

        try
        {
            server.JetStreamEnabled().ShouldBeTrue();
            server.StoreDir().ShouldBe(options.JetStream.StoreDir);

            var cfg = server.JetStreamConfig();
            cfg.ShouldNotBeNull();
            cfg!.StoreDir.ShouldBe(options.JetStream.StoreDir);
            cfg.MaxMemoryStore.ShouldBe(options.JetStream.MaxMemoryStore);
            cfg.MaxFileStore.ShouldBe(options.JetStream.MaxFileStore);
            cfg.MaxStreams.ShouldBe(options.JetStream.MaxStreams);
            cfg.MaxConsumers.ShouldBe(options.JetStream.MaxConsumers);
            cfg.Domain.ShouldBe(options.JetStream.Domain);

            cfg.MaxStreams = 99;
            server.JetStreamConfig()!.MaxStreams.ShouldBe(options.JetStream.MaxStreams);
        }
        finally
        {
            await cts.CancelAsync();
            server.Dispose();
            if (Directory.Exists(options.JetStream.StoreDir))
                Directory.Delete(options.JetStream.StoreDir, recursive: true);
        }
    }

    [Fact]
    public void Server_returns_empty_or_null_jetstream_config_when_disabled()
    {
        var server = new NatsServer(new NatsOptions
        {
            Host = "127.0.0.1",
            Port = 0,
        }, NullLoggerFactory.Instance);

        server.JetStreamEnabled().ShouldBeFalse();
        server.JetStreamConfig().ShouldBeNull();
        server.StoreDir().ShouldBe(string.Empty);
    }
}
