package com.alttd.altitudeweb.services.limits;

import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class InMemoryRateLimiterService {

    private final Map<String, RequestCounter> limiters = new ConcurrentHashMap<>();
    
    public boolean tryAcquire(String key, int limit, Duration duration) {
        RequestCounter counter = limiters.computeIfAbsent(key, k -> new RequestCounter());
        return counter.tryAcquire(limit, duration);
    }
    
    public Duration getNextResetTime(String key, Duration duration) {
        RequestCounter counter = limiters.get(key);
        if (counter == null) {
            return Duration.ZERO;
        }
        return counter.getNextResetTime(duration);
    }
    
    public int getRemainingTokens(String key, int limit, Duration duration) {
        RequestCounter counter = limiters.get(key);
        if (counter == null) {
            return limit;
        }
        return Math.max(0, limit - counter.getCurrentCount(duration));
    }


}
