using Akka.Actor;
using Akka.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.ClusterInfrastructure;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Host.Actors;
using ZB.MOM.WW.ScadaBridge.Host.Health;

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

public class ClusterActivityEvaluatorTests : IAsyncLifetime
{
    private ActorSystem? _system;

    public async Task InitializeAsync()
    {
        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://eval-test@127.0.0.1:{port}""]
        roles = [""Central""]
        min-nr-of-members = 1
    }}
}}");
        _system = ActorSystem.Create("eval-test", config);
        var cluster = Akka.Cluster.Cluster.Get(_system);
        var deadline = DateTime.UtcNow.AddSeconds(20);
        while (cluster.SelfMember.Status != Akka.Cluster.MemberStatus.Up && DateTime.UtcNow < deadline)
            await Task.Delay(100);
    }

    public async Task DisposeAsync() { if (_system != null) await _system.Terminate(); }

    [Fact]
    public void SelfIsOldest_SoleUpMember_ReturnsTrue()
    {
        var cluster = Akka.Cluster.Cluster.Get(_system!);
        Assert.True(ClusterActivityEvaluator.SelfIsOldest(cluster));
        Assert.True(ClusterActivityEvaluator.SelfIsOldest(cluster, "Central"));
    }

    [Fact]
    public void SelfIsOldest_RoleNotHeld_ReturnsFalse()
    {
        var cluster = Akka.Cluster.Cluster.Get(_system!);
        // Self doesn't carry the role => it can never host that role's singletons.
        Assert.False(ClusterActivityEvaluator.SelfIsOldest(cluster, "site-nonexistent"));
    }

    [Fact]
    public async Task ActiveNodeGate_And_NodeProvider_AgreeWithEvaluator()
    {
        // Both product gates must be backed by the oldest-member evaluator.
        // A single-node Up cluster: evaluator says true, so both must say true.
        // (Pinning test — the leader==oldest divergence is proven in Task 8's
        // two-node integration test; here we assert the wiring holds.)
        var port = FreePort();
        var self = $"akka.tcp://scadabridge@127.0.0.1:{port}";
        var akkaService = new AkkaHostedService(
            new ServiceCollection().BuildServiceProvider(),
            Options.Create(new NodeOptions { Role = "Central", NodeHostname = "127.0.0.1", RemotingPort = port }),
            Options.Create(new ClusterOptions
            {
                SeedNodes = new List<string> { self },
                SplitBrainResolverStrategy = "keep-oldest",
                StableAfter = TimeSpan.FromSeconds(3),
                HeartbeatInterval = TimeSpan.FromMilliseconds(500),
                FailureDetectionThreshold = TimeSpan.FromSeconds(2),
                MinNrOfMembers = 1,
                DownIfAlone = true,
            }),
            Options.Create(new CommunicationOptions()),
            NullLogger<AkkaHostedService>.Instance);

        var system = akkaService.GetOrCreateActorSystem();
        try
        {
            var cluster = Akka.Cluster.Cluster.Get(system);
            var deadline = DateTime.UtcNow.AddSeconds(20);
            while (cluster.SelfMember.Status != Akka.Cluster.MemberStatus.Up && DateTime.UtcNow < deadline)
                await Task.Delay(100);

            var gate = new ActiveNodeGate(akkaService);
            var provider = new AkkaClusterNodeProvider(akkaService, "Central");
            Assert.True(gate.IsActiveNode);
            Assert.True(provider.SelfIsPrimary);
        }
        finally
        {
            await system.Terminate();
        }
    }

    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;
    }
}
