using Akka.Actor;
using Akka.TestKit.Xunit2;
using NSubstitute;
using ScadaLink.Commons.Interfaces.Protocol;
using ScadaLink.Commons.Messages.DataConnection;
using ScadaLink.DataConnectionLayer.Actors;
using ScadaLink.HealthMonitoring;

namespace ScadaLink.DataConnectionLayer.Tests;

/// <summary>
/// WP-34: Tests for DataConnectionManagerActor routing and lifecycle.
/// </summary>
public class DataConnectionManagerActorTests : TestKit
{
    private readonly IDataConnectionFactory _mockFactory;
    private readonly DataConnectionOptions _options;
    private readonly ISiteHealthCollector _mockHealthCollector;

    public DataConnectionManagerActorTests()
        : base(@"akka.loglevel = DEBUG")
    {
        _mockFactory = Substitute.For<IDataConnectionFactory>();
        _mockHealthCollector = Substitute.For<ISiteHealthCollector>();
        _options = new DataConnectionOptions
        {
            ReconnectInterval = TimeSpan.FromMilliseconds(100),
            TagResolutionRetryInterval = TimeSpan.FromMilliseconds(200)
        };
    }

    [Fact]
    public void WriteToUnknownConnection_ReturnsError()
    {
        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_mockFactory, _options, _mockHealthCollector)));

        manager.Tell(new WriteTagRequest(
            "corr1", "nonexistent", "tag1", 42, DateTimeOffset.UtcNow));

        var response = ExpectMsg<WriteTagResponse>();
        Assert.False(response.Success);
        Assert.Contains("Unknown connection", response.ErrorMessage);
    }

    [Fact]
    public void SubscribeToUnknownConnection_ReturnsError()
    {
        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_mockFactory, _options, _mockHealthCollector)));

        manager.Tell(new SubscribeTagsRequest(
            "corr1", "inst1", "nonexistent", ["tag1"], DateTimeOffset.UtcNow));

        var response = ExpectMsg<SubscribeTagsResponse>();
        Assert.False(response.Success);
        Assert.Contains("Unknown connection", response.ErrorMessage);
    }

    [Fact]
    public void CreateConnection_UsesFactory()
    {
        var mockAdapter = Substitute.For<IDataConnection>();
        mockAdapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.CompletedTask);
        _mockFactory.Create("OpcUa", Arg.Any<IDictionary<string, string>>())
            .Returns(mockAdapter);

        var manager = Sys.ActorOf(Props.Create(() =>
            new DataConnectionManagerActor(_mockFactory, _options, _mockHealthCollector)));

        manager.Tell(new CreateConnectionCommand(
            "conn1", "OpcUa", new Dictionary<string, string>(), null, 3));

        // Factory should have been called
        AwaitCondition(() =>
            _mockFactory.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Create"),
            TimeSpan.FromSeconds(2));
    }
}
