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

namespace NATS.Server.Core.Tests.Server;

public class UtilitiesAndRateCounterParityBatch1Tests
{
    [Fact]
    public void ParseHostPort_uses_default_port_for_missing_zero_and_minus_one()
    {
        ServerUtilities.ParseHostPort("127.0.0.1", 4222).ShouldBe(("127.0.0.1", 4222));
        ServerUtilities.ParseHostPort("127.0.0.1:0", 4222).ShouldBe(("127.0.0.1", 4222));
        ServerUtilities.ParseHostPort("127.0.0.1:-1", 4222).ShouldBe(("127.0.0.1", 4222));
        ServerUtilities.ParseHostPort(":4333", 4222).ShouldBe(("", 4333));
    }

    [Fact]
    public void RedactUrl_helpers_redact_password_for_single_and_list_inputs()
    {
        ServerUtilities.RedactUrlString("nats://foo:bar@example.com:4222")
            .ShouldBe("nats://foo:xxxxx@example.com:4222");
        ServerUtilities.RedactUrlString("nats://example.com:4222")
            .ShouldBe("nats://example.com:4222");

        var redacted = ServerUtilities.RedactUrlList(
            ["nats://a:b@one:4222", "nats://noauth:4223"]);
        redacted[0].ShouldBe("nats://a:xxxxx@one:4222");
        redacted[1].ShouldBe("nats://noauth:4223");
    }

    [Fact]
    public void RateCounter_allow_and_count_blocked_match_go_behavior()
    {
        var rc = new RateCounter(2);

        rc.Allow().ShouldBeTrue();
        rc.Allow().ShouldBeTrue();
        rc.Allow().ShouldBeFalse();
        rc.Allow().ShouldBeFalse();

        rc.CountBlocked().ShouldBe((ulong)2);
        rc.CountBlocked().ShouldBe((ulong)0); // reset on read
    }

    [Fact]
    public void CreateRouteDialSocket_disables_keepalive()
    {
        using var socket = RouteManager.CreateRouteDialSocket();
        var keepAlive = Convert.ToInt32(socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive));
        keepAlive.ShouldBe(0);
    }
}
