namespace QuantEngine.Web.Services;

public interface IIpLockoutService
{
    bool IsLockedOut(string ipAddress);
    void RecordFailedAttempt(string ipAddress);
    void ClearFailedAttempts(string ipAddress);
}

public class IpLockoutService : IIpLockoutService
{
    private readonly Dictionary<string, (int Attempts, DateTime LockedUntil)> _attemptLog = [];
    private const int MaxFailedAttempts = 3;
    private const int LockoutDurationMinutes = 15;
    private readonly object _lock = new();

    public bool IsLockedOut(string ipAddress)
    {
        lock (_lock)
        {
            if (_attemptLog.TryGetValue(ipAddress, out var record))
            {
                if (DateTime.UtcNow < record.LockedUntil)
                    return true;

                _attemptLog.Remove(ipAddress);
            }

            return false;
        }
    }

    public void RecordFailedAttempt(string ipAddress)
    {
        lock (_lock)
        {
            if (_attemptLog.TryGetValue(ipAddress, out var record))
            {
                record.Attempts++;
                if (record.Attempts >= MaxFailedAttempts)
                {
                    record.LockedUntil = DateTime.UtcNow.AddMinutes(LockoutDurationMinutes);
                }

                _attemptLog[ipAddress] = record;
            }
            else
            {
                _attemptLog[ipAddress] = (1, DateTime.UtcNow);
            }
        }
    }

    public void ClearFailedAttempts(string ipAddress)
    {
        lock (_lock)
        {
            _attemptLog.Remove(ipAddress);
        }
    }
}
