using ColaFlow.Modules.Identity.Application.Services;
using Microsoft.Extensions.Caching.Memory;

namespace ColaFlow.Modules.Identity.Infrastructure.Services;

/// <summary>
/// In-memory rate limiting service implementation.
/// For production, consider using Redis for distributed rate limiting.
/// </summary>
public class MemoryRateLimitService : IRateLimitService
{
    private readonly IMemoryCache _cache;

    public MemoryRateLimitService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public Task<bool> IsAllowedAsync(
        string key,
        int maxAttempts,
        TimeSpan window,
        CancellationToken cancellationToken = default)
    {
        var cacheKey = $"ratelimit:{key}";

        // Get current attempt count from cache
        var attempts = _cache.GetOrCreate(cacheKey, entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = window;
            return 0;
        });

        // Check if limit exceeded
        if (attempts >= maxAttempts)
        {
            return Task.FromResult(false);
        }

        // Increment attempt count
        _cache.Set(cacheKey, attempts + 1, new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = window
        });

        return Task.FromResult(true);
    }
}
