using Akka.Actor;
using Akka.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Host.Actors;

namespace ZB.MOM.WW.ScadaBridge.Host.Tests;

public class SingletonRegistrarTests
{
    private sealed class EchoActor : ReceiveActor
    {
        public EchoActor() => ReceiveAny(m => Sender.Tell(m));
    }

    [Fact]
    public async Task Start_CreatesManagerAndProxy_WithCanonicalNames_AndDrainTask()
    {
        using var system = CreateSingleNodeClusterSystem();
        var handle = SingletonRegistrar.Start(
            system, "test-widget", Props.Create(() => new EchoActor()),
            NullLogger.Instance, drainTimeout: TimeSpan.FromSeconds(2));

        // Canonical naming preserved: <name>-singleton / <name>-proxy.
        Assert.EndsWith("/user/test-widget-singleton", handle.Manager.Path.ToString());
        Assert.EndsWith("/user/test-widget-proxy", handle.Proxy.Path.ToString());

        // Singleton answers through the proxy once the member is Up.
        var echo = await handle.Proxy.Ask<string>("hi", TimeSpan.FromSeconds(20));
        Assert.Equal("hi", echo);

        // The drain task registered on PhaseClusterLeave must stop the manager
        // during coordinated shutdown.
        await Akka.Actor.CoordinatedShutdown.Get(system).Run(
            Akka.Actor.CoordinatedShutdown.ClrExitReason.Instance);
        // Manager terminated => drain ran (GracefulStop completed or PoisonPill fallback).
        Assert.True(handle.Manager.IsNobody() || system.WhenTerminated.IsCompleted);
    }

    [Fact]
    public async Task Start_WithRoleScope_CreatesRoleScopedSingleton_ThatAnswers()
    {
        // Round-2 N5: role scoping is what kept the two SITE singletons
        // (deployment-manager, event-log-handler) hand-rolled and drain-less.
        using var system = CreateSingleNodeClusterSystem(); // roles = ["Central"]
        var handle = SingletonRegistrar.Start(
            system, "role-widget", Props.Create(() => new EchoActor()),
            NullLogger.Instance, drainTimeout: TimeSpan.FromSeconds(2), role: "Central");

        Assert.EndsWith("/user/role-widget-singleton", handle.Manager.Path.ToString());
        Assert.EndsWith("/user/role-widget-proxy", handle.Proxy.Path.ToString());

        // The node holds the role => manager instantiates the singleton and
        // the role-scoped proxy resolves it.
        var echo = await handle.Proxy.Ask<string>("hi", TimeSpan.FromSeconds(20));
        Assert.Equal("hi", echo);
    }

    private static ActorSystem CreateSingleNodeClusterSystem()
    {
        var port = FreePort();
        var config = ConfigurationFactory.ParseString($@"
akka {{
    actor.provider = cluster
    remote.dot-netty.tcp {{ hostname = ""127.0.0.1"", port = {port} }}
    cluster {{
        seed-nodes = [""akka.tcp://registrar-test@127.0.0.1:{port}""]
        roles = [""Central""]
        min-nr-of-members = 1
    }}
}}");
        return ActorSystem.Create("registrar-test", config);
    }

    private static int FreePort()
    {
        var l = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
        l.Start(); var p = ((System.Net.IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return p;
    }
}
