using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Logging.Abstractions;
using NATS.Server.Server;

namespace NATS.Server.Core.Tests;

public class AcceptLoopErrorCallbackTests
{
    [Fact]
    public void Accept_loop_reports_error_via_callback_hook()
    {
        var server = new NatsServer(new NatsOptions
        {
            Host = "127.0.0.1",
            Port = 0,
        }, NullLoggerFactory.Instance);

        Exception? capturedError = null;
        EndPoint? capturedEndpoint = null;
        var capturedDelay = TimeSpan.Zero;

        var handler = new AcceptLoopErrorHandler((ex, endpoint, delay) =>
        {
            capturedError = ex;
            capturedEndpoint = endpoint;
            capturedDelay = delay;
        });

        server.SetAcceptLoopErrorHandlerForTest(handler);

        var endpoint = new IPEndPoint(IPAddress.Loopback, 4222);
        var error = new SocketException((int)SocketError.ConnectionReset);
        var delay = TimeSpan.FromMilliseconds(20);
        server.NotifyAcceptErrorForTest(error, endpoint, delay);

        capturedError.ShouldBe(error);
        capturedEndpoint.ShouldBe(endpoint);
        capturedDelay.ShouldBe(delay);
    }
}
