using System.Collections.Concurrent;

namespace GestionaDenuncias.Shared.Services;

public sealed class LoginRateLimiter
{
    private const int MaxAttempts = 5;
    private static readonly TimeSpan Window = TimeSpan.FromMinutes(1);
    private readonly ConcurrentDictionary<string, List<DateTimeOffset>> _attempts = new();
    private readonly object _gate = new();

    public bool AllowAttempt(string key)
    {
        var now = DateTimeOffset.UtcNow;

        lock (_gate)
        {
            var entries = _attempts.GetOrAdd(key, _ => []);
            entries.RemoveAll(t => now - t > Window);

            if (entries.Count >= MaxAttempts)
            {
                return false;
            }

            entries.Add(now);
            return true;
        }
    }
}
