using System.Text.Json;
using NATS.E2E.Tests.Infrastructure;

namespace NATS.E2E.Tests;

[Collection("E2E-Monitor")]
public class MonitoringTests(MonitorServerFixture fixture)
{
    [Fact]
    public async Task Varz_ReturnsServerInfo()
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var response = await fixture.MonitorClient.GetAsync("/varz", cts.Token);
        response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);

        var json = await response.Content.ReadAsStringAsync(cts.Token);
        using var doc = JsonDocument.Parse(json);
        var root = doc.RootElement;

        root.TryGetProperty("server_name", out _).ShouldBeTrue();
        root.TryGetProperty("version", out _).ShouldBeTrue();
        root.TryGetProperty("max_payload", out _).ShouldBeTrue();
    }

    [Fact]
    public async Task Connz_ReflectsConnectedClients()
    {
        await using var client = fixture.CreateClient();
        await client.ConnectAsync();
        await client.PingAsync();

        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var response = await fixture.MonitorClient.GetAsync("/connz", cts.Token);
        response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);

        var json = await response.Content.ReadAsStringAsync(cts.Token);
        using var doc = JsonDocument.Parse(json);
        var root = doc.RootElement;

        root.TryGetProperty("num_connections", out var numConns).ShouldBeTrue();
        numConns.GetInt32().ShouldBeGreaterThanOrEqualTo(1);
    }

    [Fact]
    public async Task Healthz_ReturnsOk()
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var response = await fixture.MonitorClient.GetAsync("/healthz", cts.Token);
        response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
    }
}
