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

namespace NATS.Server.Mqtt.Tests.Mqtt;

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

        using var client = new TcpClient();
        await client.ConnectAsync(IPAddress.Loopback, listener.Port);
        var stream = client.GetStream();

        await MqttRuntimeWire.WriteLineAsync(stream, "CONNECT keepalive-client keepalive=1");
        (await MqttRuntimeWire.ReadLineAsync(stream, 1000)).ShouldBe("CONNACK");

        // Poll until the server closes the connection due to keepalive expiry (keepalive=1s)
        var disconnected = await PollHelper.WaitUntilAsync(async () =>
        {
            var result = await MqttRuntimeWire.ReadRawAsync(stream, 200);
            return result == null;
        }, timeoutMs: 5000, intervalMs: 100);
        disconnected.ShouldBeTrue("Server should disconnect idle client after keepalive timeout");
    }
}
