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

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

/// <summary>
/// Review 01 [Medium]: the health-report transport is now an ACKED round-trip.
/// SendAsync completes when central acks Accepted:true, throws when the ack is
/// not-accepted, and throws when no actor answers (Ask timeout / system not
/// started) — the fault the sender's counter-restore path depends on.
/// </summary>
public sealed class AkkaHealthReportTransportTests
{
    private sealed class AckActor : ReceiveActor
    {
        public AckActor(bool accepted) => Receive<SiteHealthReport>(r =>
            Sender.Tell(new SiteHealthReportAck(
                r.SiteId, r.SequenceNumber, accepted, accepted ? null : "rejected by test")));
    }

    private static SiteHealthReport SampleReport(long seq = 1) =>
        new("site-a", seq, DateTimeOffset.UtcNow,
            new Dictionary<string, ConnectionHealth>(),
            new Dictionary<string, TagResolutionStatus>(),
            0, 0, new Dictionary<string, int>(), 0, 0, 0, 0);

    private static AkkaHostedService BuildService(out ActorSystem system)
    {
        var port = FreePort();
        var self = $"akka.tcp://scadabridge@127.0.0.1:{port}";
        var svc = new AkkaHostedService(
            new ServiceCollection().BuildServiceProvider(),
            Options.Create(new NodeOptions { Role = "Site", 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);
        system = svc.GetOrCreateActorSystem();
        return svc;
    }

    [Fact]
    public async Task SendAsync_AckedAccepted_Completes()
    {
        var svc = BuildService(out var system);
        try
        {
            system.ActorOf(Props.Create(() => new AckActor(true)), "site-communication");
            var transport = new AkkaHealthReportTransport(svc);
            await transport.SendAsync(SampleReport(), CancellationToken.None);
        }
        finally { await system.Terminate(); }
    }

    [Fact]
    public async Task SendAsync_AckedNotAccepted_Throws()
    {
        var svc = BuildService(out var system);
        try
        {
            system.ActorOf(Props.Create(() => new AckActor(false)), "site-communication");
            var transport = new AkkaHealthReportTransport(svc);
            await Assert.ThrowsAsync<InvalidOperationException>(
                () => transport.SendAsync(SampleReport(), CancellationToken.None));
        }
        finally { await system.Terminate(); }
    }

    [Fact]
    public async Task SendAsync_NoResponder_Throws()
    {
        var svc = BuildService(out var system);
        try
        {
            // No actor at /user/site-communication => the Ask times out and faults.
            var transport = new AkkaHealthReportTransport(svc);
            await Assert.ThrowsAnyAsync<Exception>(
                () => transport.SendAsync(SampleReport(), CancellationToken.None));
        }
        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;
    }
}
