using Microsoft.Extensions.Caching.Memory;

namespace Nalu.Web.Services;

/// <summary>
/// Tracks suspicious-input hits per API key and throttles when a key
/// exceeds the hit threshold within the rolling window.
/// Fail-open: on any internal error the request is allowed through.
/// </summary>
public class SuspiciousRateLimiter(IMemoryCache cache, ILogger<SuspiciousRateLimiter> logger)
{
    private const int    MaxHits       = 5;
    private static readonly TimeSpan Window = TimeSpan.FromMinutes(10);

    /// <summary>
    /// Records one suspicious hit for <paramref name="key"/> and returns
    /// true if the key is now throttled (hit count exceeds threshold).
    /// </summary>
    public bool RecordAndCheck(string key)
    {
        if (string.IsNullOrWhiteSpace(key)) return false;

        try
        {
            var cacheKey = $"suspicious_hits:{key}";
            var hits = cache.GetOrCreate(cacheKey, e =>
            {
                e.AbsoluteExpirationRelativeToNow = Window;
                return 0;
            });

            hits++;
            cache.Set(cacheKey, hits, Window);

            if (hits >= MaxHits)
            {
                logger.LogWarning(
                    "API key throttled after {Hits} suspicious inputs in {Window}: {Key}",
                    hits, Window, key[..Math.Min(key.Length, 8)] + "…");
                return true;
            }
        }
        catch (Exception ex)
        {
            logger.LogDebug(ex, "SuspiciousRateLimiter error — fail-open");
        }

        return false;
    }
}
