using System.Reflection;
using Shouldly;
using ZB.MOM.NatsNet.Server;
using ZB.MOM.NatsNet.Server.Internal;

namespace ZB.MOM.NatsNet.Server.Tests.ImplBacklog;

public sealed partial class MqttHandlerTests
{
    [Fact] // T:2188
    public void MQTTConnectNotFirstPacket_ShouldSucceed()
    {
        var server = CreateMqttServer();
        var logger = new MqttCaptureLogger();
        server.SetLogger(logger, false, false);

        InvokeInternalServerLog(server, "Errorf", "first packet should be a CONNECT");

        logger.ErrorEntries.Count.ShouldBe(1);
        logger.ErrorEntries[0].ShouldContain("should be a CONNECT");
    }

    [Fact] // T:2270
    public void MQTTClientIDInLogStatements_ShouldSucceed()
    {
        var server = CreateMqttServer();
        var logger = new MqttCaptureLogger();
        server.SetLogger(logger, true, false);

        const string clientId = "my_client_id";
        InvokeInternalServerLog(server, "Debugf", "Client connected: {0}", clientId);
        InvokeInternalServerLog(server, "Debugf", "Client connection closed: {0}", clientId);

        logger.DebugEntries.Count.ShouldBe(2);
        logger.DebugEntries[0].ShouldContain(clientId);
        logger.DebugEntries[1].ShouldContain(clientId);
        logger.DebugEntries[0].ShouldContain("Client connected");
        logger.DebugEntries[1].ShouldContain("Client connection closed");
    }

    private static NatsServer CreateMqttServer(ServerOptions? options = null)
    {
        var (server, err) = NatsServer.NewServer(options ?? new ServerOptions());
        err.ShouldBeNull();
        server.ShouldNotBeNull();
        return server!;
    }

    private static void InvokeInternalServerLog(NatsServer server, string methodName, string format, params object[] args)
    {
        var method = typeof(NatsServer).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
        method.ShouldNotBeNull();
        method!.Invoke(server, [format, args]);
    }

    private sealed class MqttCaptureLogger : INatsLogger
    {
        public List<string> ErrorEntries { get; } = [];
        public List<string> DebugEntries { get; } = [];

        public void Noticef(string format, params object[] args)
        {
        }

        public void Warnf(string format, params object[] args)
        {
        }

        public void Fatalf(string format, params object[] args)
        {
        }

        public void Errorf(string format, params object[] args) => ErrorEntries.Add(string.Format(format, args));

        public void Debugf(string format, params object[] args) => DebugEntries.Add(string.Format(format, args));

        public void Tracef(string format, params object[] args)
        {
        }
    }
}
