using NATS.Client.Core;
using NATS.E2E.Tests.Infrastructure;

namespace NATS.E2E.Tests;

[Collection("E2E-TLS")]
public class TlsTests(TlsServerFixture fixture)
{
    [Fact]
    public async Task Tls_ClientConnectsSecurely()
    {
        await using var client = fixture.CreateTlsClient();
        await client.ConnectAsync();

        await client.PingAsync();

        client.ConnectionState.ShouldBe(NatsConnectionState.Open);
    }

    [Fact]
    public async Task Tls_PlainTextConnection_Rejected()
    {
        await using var client = fixture.CreatePlainClient();

        var threw = false;
        try
        {
            await client.ConnectAsync();
            await client.PingAsync();
        }
        catch (Exception)
        {
            threw = true;
        }

        threw.ShouldBeTrue();
    }

    [Fact]
    public async Task Tls_PubSub_WorksOverEncryptedConnection()
    {
        await using var pub = fixture.CreateTlsClient();
        await using var sub = fixture.CreateTlsClient();

        await pub.ConnectAsync();
        await sub.ConnectAsync();

        await using var subscription = await sub.SubscribeCoreAsync<string>("tls.pubsub.test");
        await sub.PingAsync();

        await pub.PublishAsync("tls.pubsub.test", "secure-message");

        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var msg = await subscription.Msgs.ReadAsync(cts.Token);

        msg.Data.ShouldBe("secure-message");
    }
}
