using System.Text;

namespace ZB.MOM.NatsNet.Server;

internal sealed partial class NatsConsumer
{
    private string? _lastAdvisorySubject;
    private byte[]? _lastAdvisoryPayload;
    private DateTime _lastAdvisorySent;

    internal bool SendAdvisory(string subject, object advisory)
    {
        if (string.IsNullOrWhiteSpace(subject) || advisory is null)
            return false;

        _mu.EnterWriteLock();
        try
        {
            _lastAdvisorySubject = subject;
            _lastAdvisoryPayload = Encoding.UTF8.GetBytes(advisory.ToString() ?? string.Empty);
            _lastAdvisorySent = DateTime.UtcNow;
            return true;
        }
        finally
        {
            _mu.ExitWriteLock();
        }
    }

    internal bool SendDeleteAdvisoryLocked() =>
        SendAdvisory($"{JsApiSubjects.JsAdvisoryConsumerDeleted}.{Stream}.{Name}", new { action = "delete" });

    internal bool SendPinnedAdvisoryLocked(string pinId) =>
        SendAdvisory($"{JsApiSubjects.JsAdvisoryConsumerPinned}.{Stream}.{Name}", new { pin = pinId });

    internal bool SendUnpinnedAdvisoryLocked(string pinId) =>
        SendAdvisory($"{JsApiSubjects.JsAdvisoryConsumerUnpinned}.{Stream}.{Name}", new { pin = pinId });

    internal bool SendCreateAdvisory() =>
        SendAdvisory($"{JsApiSubjects.JsAdvisoryConsumerCreated}.{Stream}.{Name}", new { action = "create" });

    internal bool SendPauseAdvisoryLocked(DateTime pauseUntil) =>
        SendAdvisory($"{JsApiSubjects.JsAdvisoryConsumerPause}.{Stream}.{Name}", new { pauseUntil });
}
