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

namespace NATS.Server.Tests;

public class JetStreamInternalClientRuntimeTests
{
    [Fact]
    public async Task Internal_jetstream_client_is_created_bound_to_sys_account_and_used_by_jetstream_service_lifecycle()
    {
        var options = new NatsOptions
        {
            Host = "127.0.0.1",
            Port = 0,
            JetStream = new JetStreamOptions
            {
                StoreDir = Path.Combine(Path.GetTempPath(), $"nats-js-runtime-{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();

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

        var serviceField = typeof(NatsServer).GetField("_jetStreamService", BindingFlags.Instance | BindingFlags.NonPublic);
        serviceField.ShouldNotBeNull();

        var service = serviceField!.GetValue(server) as JetStreamService;
        service.ShouldNotBeNull();
        service!.InternalClient.ShouldBeSameAs(internalClient);
        service.IsRunning.ShouldBeTrue();

        await server.ShutdownAsync();
        service.IsRunning.ShouldBeFalse();
    }
}
