using Microsoft.Extensions.Logging.Abstractions;
using NATS.Server.Configuration;
using NATS.Server.JetStream;
using System.Reflection;

namespace NATS.Server.JetStream.Tests;

public class JetStreamInternalClientTests
{
    [Fact]
    public async Task JetStream_enabled_server_creates_internal_jetstream_client_and_keeps_it_account_scoped()
    {
        var options = new NatsOptions
        {
            Host = "127.0.0.1",
            Port = 0,
            JetStream = new JetStreamOptions
            {
                StoreDir = Path.Combine(Path.GetTempPath(), $"nats-js-internal-{Guid.NewGuid():N}"),
                MaxMemoryStore = 1024 * 1024,
                MaxFileStore = 10 * 1024 * 1024,
            },
        };

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

        server.JetStreamInternalClient.ShouldNotBeNull();
        server.JetStreamInternalClient!.Kind.ShouldBe(ClientKind.JetStream);
        server.JetStreamInternalClient.Account?.Name.ShouldBe("$SYS");

        var serviceField = typeof(NatsServer).GetField("_jetStreamService", BindingFlags.Instance | BindingFlags.NonPublic);
        serviceField.ShouldNotBeNull();
        (serviceField!.GetValue(server) as JetStreamService).ShouldNotBeNull();
    }
}
