using System.Net;
using System.Net.Sockets;
using NATS.Server.Mqtt;

namespace NATS.Server.Tests;

public class MqttPublishSubscribeParityTests
{
    [Fact]
    public async Task Mqtt_publish_only_reaches_matching_topic_subscribers()
    {
        await using var listener = new MqttListener("127.0.0.1", 0);
        using var cts = new CancellationTokenSource();
        await listener.StartAsync(cts.Token);

        using var sub = new TcpClient();
        await sub.ConnectAsync(IPAddress.Loopback, listener.Port);
        var subStream = sub.GetStream();
        await MqttTestWire.WriteLineAsync(subStream, "CONNECT sub");
        _ = await MqttTestWire.ReadLineAsync(subStream, 1000);
        await MqttTestWire.WriteLineAsync(subStream, "SUB sensors.temp");
        _ = await MqttTestWire.ReadLineAsync(subStream, 1000);

        using var pub = new TcpClient();
        await pub.ConnectAsync(IPAddress.Loopback, listener.Port);
        var pubStream = pub.GetStream();
        await MqttTestWire.WriteLineAsync(pubStream, "CONNECT pub");
        _ = await MqttTestWire.ReadLineAsync(pubStream, 1000);
        await MqttTestWire.WriteLineAsync(pubStream, "PUB sensors.humidity 90");

        (await MqttTestWire.ReadLineAsync(subStream, 150)).ShouldBeNull();
    }
}
