using System.Reflection;
using Microsoft.Extensions.Logging.Abstractions;
using NATS.Server.Monitoring;

namespace NATS.Server.Core.Tests.Internal;

public class InternalDsPeriodicSamplerParityTests
{
    [Fact]
    [SlopwatchSuppress("SW004", "Test must observe a real 1-second CPU sampling timer tick; wall-clock elapsed time is the observable under test")]
    public async Task VarzHandler_uses_periodic_background_cpu_sampler()
    {
        var options = new NatsOptions { Host = "127.0.0.1", Port = 0 };
        var server = new NatsServer(options, NullLoggerFactory.Instance);
        using var cts = new CancellationTokenSource();
        _ = server.StartAsync(cts.Token);
        await server.WaitForReadyAsync();

        try
        {
            using var handler = new VarzHandler(server, options, NullLoggerFactory.Instance);
            var field = typeof(VarzHandler).GetField("_lastCpuSampleTime", BindingFlags.NonPublic | BindingFlags.Instance);
            field.ShouldNotBeNull();

            var before = (DateTime)field!.GetValue(handler)!;
            await Task.Delay(TimeSpan.FromMilliseconds(1200));
            var after = (DateTime)field.GetValue(handler)!;

            after.ShouldBeGreaterThan(before);
        }
        finally
        {
            await cts.CancelAsync();
            server.Dispose();
        }
    }
}
