using System.Text.Json;
using System.Text;

namespace NATS.Server.Monitoring.Tests;

public class ConnzParityFieldTests
{
    [Fact]
    public async Task Connz_includes_identity_tls_and_proxy_parity_fields()
    {
        await using var fx = await MonitoringParityFixture.StartAsync();
        var jwt = BuildJwt("UISSUER", ["team:core", "tier:gold"]);
        await fx.ConnectClientAsync("proxy:edge", "orders.created", jwt);

        var connz = fx.GetConnz("?subs=detail&auth=true");
        connz.Conns.ShouldNotBeEmpty();
        var conn = connz.Conns.Single(c => c.AuthorizedUser == "proxy:edge");
        conn.Proxy.ShouldNotBeNull();
        conn.Proxy.Key.ShouldBe("edge");
        conn.Jwt.ShouldBe(jwt);
        conn.IssuerKey.ShouldBe("UISSUER");
        conn.Tags.ShouldContain("team:core");

        var json = JsonSerializer.Serialize(connz);
        json.ShouldContain("tls_peer_cert_subject");
        json.ShouldContain("tls_peer_certs");
        json.ShouldContain("issuer_key");
        json.ShouldContain("\"tags\"");
        json.ShouldContain("proxy");
        json.ShouldNotContain("jwt_issuer_key");
    }

    private static string BuildJwt(string issuer, string[] tags)
    {
        static string B64Url(string json)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(json))
                .TrimEnd('=')
                .Replace('+', '-')
                .Replace('/', '_');
        }

        var header = B64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}");
        var payload = B64Url(JsonSerializer.Serialize(new
        {
            iss = issuer,
            nats = new
            {
                tags,
            },
        }));
        return $"{header}.{payload}.eA";
    }
}
