using System.Collections.Concurrent;

namespace AiLogia.Auth.Services;

public sealed class SimpleRateLimiter
{
    private readonly ConcurrentDictionary<long, DateTime> _last = new();
    private readonly TimeSpan _window;
    public SimpleRateLimiter(TimeSpan window) => _window = window;

    public bool TryHit(long tgId, out TimeSpan retryAfter)
    {
        var now = DateTime.UtcNow;
        var last = _last.GetOrAdd(tgId, _ => DateTime.MinValue);
        if (now - last < _window)
        {
            retryAfter = _window - (now - last);
            return false;
        }
        _last[tgId] = now;
        retryAfter = TimeSpan.Zero;
        return true;
    }
}