using Akka.Actor;
using Akka.Hosting;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.ControlPlane;

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

/// <summary>
///     AdminUI-side <see cref="IAuditWriter" /> adapter. Forwards canonical
///     <see cref="AuditEvent" />s to the ControlPlane <see cref="AuditWriterActorKey" /> cluster
///     singleton (resolved from <see cref="ActorRegistry" /> at construction, mirroring
///     <c>AdminOperationsClient</c>), which batches and persists them to <c>ConfigAuditLog</c>.
///     Emission is fire-and-forget via <c>Tell</c>: best-effort and never blocks or throws to the
///     caller, matching the audit-writer contract.
/// </summary>
public sealed class ActorAuditWriter : IAuditWriter
{
    private readonly IActorRef _proxy;

    /// <summary>Initializes a new instance of the <see cref="ActorAuditWriter" /> class.</summary>
    /// <param name="registry">The actor registry used to resolve the AuditWriter singleton proxy.</param>
    public ActorAuditWriter(ActorRegistry registry)
    {
        _proxy = registry.Get<AuditWriterActorKey>();
    }

    /// <summary>
    ///     Forwards the event to the AuditWriter singleton via <c>Tell</c> and returns immediately.
    ///     The actual persistence happens asynchronously on the actor's next flush.
    /// </summary>
    /// <param name="evt">The canonical audit event to persist.</param>
    /// <param name="ct">Unused — enqueue is synchronous and non-blocking.</param>
    /// <returns>A completed task.</returns>
    public Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
    {
        _proxy.Tell(evt);
        return Task.CompletedTask;
    }
}
