using Akka.Actor;
using Akka.TestKit.Xunit2;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors;
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;

namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;

/// <summary>
/// Test Bindings (one-shot live read of bound tags): the site-side
/// <see cref="DataConnectionManagerActor"/> + child
/// <see cref="DataConnectionActor"/> together resolve
/// <see cref="ReadTagValuesCommand"/> against the live adapter and surface
/// every outcome as either a per-tag <see cref="TagReadOutcome"/> or a typed
/// connection-level <see cref="ReadTagValuesFailure"/>. The split mirrors the
/// browse handler: the manager owns
/// <see cref="ReadTagValuesFailureKind.ConnectionNotFound"/> (only it knows
/// the per-site connection set); everything else lives in the child where the
/// adapter is held — <see cref="ReadTagValuesFailureKind.ConnectionNotConnected"/>
/// from the pre-call status check, <see cref="ReadTagValuesFailureKind.Timeout"/>
/// / <see cref="ReadTagValuesFailureKind.ServerError"/> from the adapter call.
/// </summary>
public class DataConnectionManagerReadTagValuesHandlerTests : TestKit
{
    private readonly IDataConnectionFactory _factory;
    private readonly ISiteHealthCollector _healthCollector;
    private readonly DataConnectionOptions _options;

    public DataConnectionManagerReadTagValuesHandlerTests()
        : base(@"akka.loglevel = WARNING")
    {
        _factory = Substitute.For<IDataConnectionFactory>();
        _healthCollector = Substitute.For<ISiteHealthCollector>();
        _options = new DataConnectionOptions
        {
            ReconnectInterval = TimeSpan.FromSeconds(30),
            TagResolutionRetryInterval = TimeSpan.FromSeconds(30),
        };
    }

    [Fact]
    public void Unknown_connection_name_returns_ConnectionNotFound()
    {
        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_factory, _options, _healthCollector, null)));

        // No CreateConnectionCommand sent — the manager has zero children, so
        // any read must be rejected with ConnectionNotFound (only the manager
        // has site-level visibility into the connection set).
        manager.Tell(new ReadTagValuesCommand("unknown-connection", new[] { "ns=2;s=A" }));

        var reply = ExpectMsg<ReadTagValuesResult>();
        Assert.NotNull(reply.Failure);
        Assert.Equal(ReadTagValuesFailureKind.ConnectionNotFound, reply.Failure!.Kind);
        Assert.Empty(reply.Outcomes);
    }

    [Fact]
    public void Adapter_not_connected_returns_ConnectionNotConnected()
    {
        // Adapter that reports Disconnected — the child actor's pre-call
        // status check must short-circuit to ConnectionNotConnected without
        // calling ReadBatchAsync (avoids the per-tag "client is not
        // connected" noise that the OpcUa adapter would otherwise produce).
        var adapter = Substitute.For<IDataConnection>();
        adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.FromException(new InvalidOperationException("simulated failure")));
        adapter.Status.Returns(ConnectionHealth.Disconnected);
        _factory.Create("OpcUa", Arg.Any<IDictionary<string, string>>()).Returns(adapter);

        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_factory, _options, _healthCollector, null)));
        manager.Tell(new CreateConnectionCommand(
            "conn-down", "OpcUa", new Dictionary<string, string>(), null, 3));

        // Wait for the child actor to spin up; the read handler runs in every
        // lifecycle state, so we don't need to wait for a specific Become.
        AwaitCondition(
            () => _factory.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Create"),
            TimeSpan.FromSeconds(2));

        manager.Tell(new ReadTagValuesCommand("conn-down", new[] { "ns=2;s=A" }));

        var reply = ExpectMsg<ReadTagValuesResult>(TimeSpan.FromSeconds(3));
        Assert.NotNull(reply.Failure);
        Assert.Equal(ReadTagValuesFailureKind.ConnectionNotConnected, reply.Failure!.Kind);
        Assert.Empty(reply.Outcomes);

        // ReadBatchAsync must NOT be called when the status guard short-circuits.
        adapter.DidNotReceive().ReadBatchAsync(Arg.Any<IEnumerable<string>>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public void Success_path_maps_results_to_TagReadOutcomes()
    {
        var adapter = Substitute.For<IDataConnection>();
        adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.CompletedTask);
        adapter.Status.Returns(ConnectionHealth.Connected);

        var ts = new DateTimeOffset(2026, 5, 28, 12, 0, 0, TimeSpan.Zero);
        var batch = new Dictionary<string, ReadResult>
        {
            ["ns=2;s=A"] = new ReadResult(true, new TagValue(42.7, QualityCode.Good, ts), null),
            // Adapter-reported per-tag failure (e.g. unknown node id): mapped to
            // a failure TagReadOutcome with Quality=Bad and Value=null.
            ["ns=2;s=B"] = new ReadResult(false, null, "BadNodeIdUnknown"),
        };
        adapter.ReadBatchAsync(Arg.Any<IEnumerable<string>>(), Arg.Any<CancellationToken>())
            .Returns(batch);
        _factory.Create("OpcUa", Arg.Any<IDictionary<string, string>>()).Returns(adapter);

        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_factory, _options, _healthCollector, null)));
        manager.Tell(new CreateConnectionCommand(
            "conn-ok", "OpcUa", new Dictionary<string, string>(), null, 3));

        AwaitCondition(
            () => _factory.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Create"),
            TimeSpan.FromSeconds(2));

        manager.Tell(new ReadTagValuesCommand("conn-ok", new[] { "ns=2;s=A", "ns=2;s=B" }));

        var reply = ExpectMsg<ReadTagValuesResult>(TimeSpan.FromSeconds(3));
        Assert.Null(reply.Failure);
        Assert.Equal(2, reply.Outcomes.Count);

        var aOutcome = reply.Outcomes.Single(o => o.TagPath == "ns=2;s=A");
        Assert.True(aOutcome.Success);
        Assert.Equal(42.7, aOutcome.Value);
        Assert.Equal("Good", aOutcome.Quality);
        Assert.Equal(ts, aOutcome.Timestamp);
        Assert.Null(aOutcome.ErrorMessage);

        var bOutcome = reply.Outcomes.Single(o => o.TagPath == "ns=2;s=B");
        Assert.False(bOutcome.Success);
        Assert.Null(bOutcome.Value);
        Assert.Equal("Bad", bOutcome.Quality);
        Assert.Equal("BadNodeIdUnknown", bOutcome.ErrorMessage);
    }

    [Fact]
    public void Adapter_OperationCancelled_returns_Timeout()
    {
        var adapter = Substitute.For<IDataConnection>();
        adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.CompletedTask);
        adapter.Status.Returns(ConnectionHealth.Connected);
        adapter.ReadBatchAsync(Arg.Any<IEnumerable<string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.FromException<IReadOnlyDictionary<string, ReadResult>>(
                new OperationCanceledException("test cancel")));
        _factory.Create("OpcUa", Arg.Any<IDictionary<string, string>>()).Returns(adapter);

        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_factory, _options, _healthCollector, null)));
        manager.Tell(new CreateConnectionCommand(
            "conn-slow", "OpcUa", new Dictionary<string, string>(), null, 3));

        AwaitCondition(
            () => _factory.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Create"),
            TimeSpan.FromSeconds(2));

        manager.Tell(new ReadTagValuesCommand("conn-slow", new[] { "ns=2;s=A" }));

        var reply = ExpectMsg<ReadTagValuesResult>(TimeSpan.FromSeconds(3));
        Assert.NotNull(reply.Failure);
        Assert.Equal(ReadTagValuesFailureKind.Timeout, reply.Failure!.Kind);
        Assert.Empty(reply.Outcomes);
    }
}
