using Akka.Actor;
using Akka.Event;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ScadaLink.Host.Actors;

namespace ScadaLink.Host.Tests;

/// <summary>
/// WP-15: Tests for DeadLetterMonitorActor.
/// </summary>
public class DeadLetterMonitorTests : TestKit
{
    private readonly ILogger<DeadLetterMonitorActor> _logger =
        NullLoggerFactory.Instance.CreateLogger<DeadLetterMonitorActor>();

    [Fact]
    public void DeadLetterMonitor_StartsWithZeroCount()
    {
        var monitor = Sys.ActorOf(Props.Create(() => new DeadLetterMonitorActor(_logger)));

        monitor.Tell(GetDeadLetterCount.Instance);
        var response = ExpectMsg<DeadLetterCountResponse>();

        Assert.Equal(0, response.Count);
    }

    [Fact]
    public void DeadLetterMonitor_IncrementsOnDeadLetter()
    {
        var monitor = Sys.ActorOf(Props.Create(() => new DeadLetterMonitorActor(_logger)));

        // Ensure actor has started and subscribed by sending a message and waiting for response
        monitor.Tell(GetDeadLetterCount.Instance);
        ExpectMsg<DeadLetterCountResponse>();

        // Now publish dead letters — actor is guaranteed to be subscribed
        Sys.EventStream.Publish(new DeadLetter("test-message-1", Sys.DeadLetters, Sys.DeadLetters));
        Sys.EventStream.Publish(new DeadLetter("test-message-2", Sys.DeadLetters, Sys.DeadLetters));

        // Use AwaitAssert to handle async event delivery
        AwaitAssert(() =>
        {
            monitor.Tell(GetDeadLetterCount.Instance);
            var response = ExpectMsg<DeadLetterCountResponse>();
            Assert.Equal(2, response.Count);
        });
    }

    [Fact]
    public void DeadLetterMonitor_CountAccumulates()
    {
        var monitor = Sys.ActorOf(Props.Create(() => new DeadLetterMonitorActor(_logger)));

        // Ensure actor is started and subscribed
        monitor.Tell(GetDeadLetterCount.Instance);
        ExpectMsg<DeadLetterCountResponse>();

        // Send 5 dead letters
        for (var i = 0; i < 5; i++)
        {
            Sys.EventStream.Publish(
                new DeadLetter($"message-{i}", Sys.DeadLetters, Sys.DeadLetters));
        }

        AwaitAssert(() =>
        {
            monitor.Tell(GetDeadLetterCount.Instance);
            var response = ExpectMsg<DeadLetterCountResponse>();
            Assert.Equal(5, response.Count);
        });
    }
}
