using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Hubs;

/// <summary>
///     Akka actor that subscribes to the <c>driver-resilience-status</c> DistributedPubSub topic and
///     upserts every <see cref="DriverResilienceStatusChanged"/> snapshot into the in-process
///     <see cref="IDriverResilienceStatusStore"/>. The driver status panel's resilience section reads
///     that store directly (per the house ban on server-side self-targeted SignalR connections), so —
///     unlike <see cref="DriverStatusSignalRBridge"/> — there is no SignalR hub here; resilience has no
///     browser-JS consumer. Spawned per admin-role node by <c>WithOtOpcUaSignalRBridges</c>.
/// </summary>
public sealed class DriverResilienceStatusBridge : ReceiveActor
{
    public const string TopicName = DriverResilienceStatusChanged.TopicName;

    private readonly IDriverResilienceStatusStore _store;

    /// <summary>Creates actor props for a <see cref="DriverResilienceStatusBridge"/>.</summary>
    /// <param name="store">Resilience status store updated on every forwarded snapshot.</param>
    /// <returns>An Akka.NET <see cref="Props"/> instance for spawning the bridge actor.</returns>
    public static Props Props(IDriverResilienceStatusStore store) =>
        Akka.Actor.Props.Create(() => new DriverResilienceStatusBridge(store));

    /// <summary>Initializes a new instance of <see cref="DriverResilienceStatusBridge"/>.</summary>
    /// <param name="store">Resilience status store updated on every forwarded snapshot.</param>
    public DriverResilienceStatusBridge(IDriverResilienceStatusStore store)
    {
        _store = store;
        Receive<DriverResilienceStatusChanged>(msg => _store.Upsert(msg));
        Receive<SubscribeAck>(_ => { /* DPS confirmation */ });
    }

    /// <inheritdoc />
    protected override void PreStart() =>
        DistributedPubSub.Get(Context.System).Mediator.Tell(new Subscribe(TopicName, Self));
}
