using EonaCat.LogStack.Core;
using System;

namespace EonaCat.LogStack.Boosters;

/// <summary>
/// Rate limiting booster that throttles log events
/// </summary>
public sealed class RateLimitingBooster : BoosterBase
{
    private readonly int _maxEventsPerSecond;
    private DateTime _lastResetTime;
    private int _eventCount;
    private readonly object _lock = new object();

    public RateLimitingBooster(int maxEventsPerSecond = 1000) : base("RateLimiting")
    {
        if (maxEventsPerSecond <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(maxEventsPerSecond));
        }

        _maxEventsPerSecond = maxEventsPerSecond;
        _lastResetTime = DateTime.UtcNow;
    }

    public override bool Boost(ref LogEventBuilder builder)
    {
        lock (_lock)
        {
            var now = DateTime.UtcNow;
            var elapsed = (now - _lastResetTime).TotalSeconds;

            if (elapsed >= 1.0)
            {
                _lastResetTime = now;
                _eventCount = 0;
            }

            _eventCount++;
            return _eventCount <= _maxEventsPerSecond;
        }
    }

    /// <summary>
    /// Gets current rate limiting statistics
    /// </summary>
    public (int current, int limit) GetStatistics()
    {
        lock (_lock)
        {
            return (_eventCount, _maxEventsPerSecond);
        }
    }
}
