using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using NATS.Server.Monitoring;

namespace NATS.Server.Monitoring.Tests.Monitoring;

public class TlsPeerCertParityTests
{
    [Fact]
    public void TLSPeerCert_serializes_go_shape_fields()
    {
        var cert = new TLSPeerCert
        {
            Subject = "CN=peer",
            SubjectPKISha256 = new string('a', 64),
            CertSha256 = new string('b', 64),
        };

        var json = JsonSerializer.Serialize(cert);

        json.ShouldContain("\"subject\":\"CN=peer\"");
        json.ShouldContain("\"subject_pk_sha256\":");
        json.ShouldContain("\"cert_sha256\":");
    }

    [Fact]
    public void TlsPeerCertMapper_produces_subject_and_sha256_values_from_certificate()
    {
        using var rsa = RSA.Create(2048);
        var req = new CertificateRequest("CN=peer", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));

        var mapped = TlsPeerCertMapper.FromCertificate(cert);

        mapped.Length.ShouldBe(1);
        mapped[0].Subject.ShouldContain("CN=peer");
        mapped[0].SubjectPKISha256.Length.ShouldBe(64);
        mapped[0].CertSha256.Length.ShouldBe(64);
    }

    [Fact]
    public void ConnInfo_json_includes_tls_peer_certs_array()
    {
        var info = new ConnInfo
        {
            Cid = 1,
            TlsPeerCertSubject = "CN=peer",
            TlsPeerCerts =
            [
                new TLSPeerCert
                {
                    Subject = "CN=peer",
                    SubjectPKISha256 = new string('c', 64),
                    CertSha256 = new string('d', 64),
                },
            ],
        };

        var json = JsonSerializer.Serialize(info);
        json.ShouldContain("\"tls_peer_certs\":[");
        json.ShouldContain("\"subject_pk_sha256\":");
        json.ShouldContain("\"cert_sha256\":");
    }
}
