using Akka.Actor;
using Akka.Event;
using Microsoft.Extensions.Logging;
using ScadaLink.HealthMonitoring;

namespace ScadaLink.Host.Actors;

/// <summary>
/// Subscribes to Akka.NET dead letter events, logs them, and tracks count
/// for health monitoring integration.
/// </summary>
public class DeadLetterMonitorActor : ReceiveActor
{
    private long _deadLetterCount;
    private readonly ISiteHealthCollector? _healthCollector;

    public DeadLetterMonitorActor(ILogger<DeadLetterMonitorActor> logger, ISiteHealthCollector? healthCollector = null)
    {
        _healthCollector = healthCollector;

        Receive<DeadLetter>(dl =>
        {
            _deadLetterCount++;
            _healthCollector?.IncrementDeadLetter();
            logger.LogWarning(
                "Dead letter: {MessageType} from {Sender} to {Recipient}",
                dl.Message.GetType().Name,
                dl.Sender,
                dl.Recipient);
        });

        Receive<GetDeadLetterCount>(_ => Sender.Tell(new DeadLetterCountResponse(_deadLetterCount)));
    }

    protected override void PreStart()
    {
        Context.System.EventStream.Subscribe(Self, typeof(DeadLetter));
    }

    protected override void PostStop()
    {
        Context.System.EventStream.Unsubscribe(Self, typeof(DeadLetter));
    }
}

/// <summary>
/// Message to request the current dead letter count.
/// </summary>
public sealed class GetDeadLetterCount
{
    public static readonly GetDeadLetterCount Instance = new();
    private GetDeadLetterCount() { }
}

/// <summary>
/// Response containing the current dead letter count.
/// </summary>
public sealed record DeadLetterCountResponse(long Count);
