const WINDOW_MS = 60_000;
function limiter(defaultLimit) {
    const windows = new Map();
    let limit = defaultLimit;
    return {
        allow(key) {
            const now = Date.now();
            const current = windows.get(key);
            if (!current || now - current.startedAt >= WINDOW_MS) {
                windows.set(key, { startedAt: now, count: 1 });
                if (windows.size > 10_000) {
                    for (const [k, w] of windows) {
                        if (now - w.startedAt >= WINDOW_MS)
                            windows.delete(k);
                    }
                }
                return true;
            }
            if (current.count >= limit)
                return false;
            current.count += 1;
            return true;
        },
        setLimitForTest(next) {
            limit = next;
            windows.clear();
        },
        reset() {
            windows.clear();
        },
    };
}
export const joinAttempts = limiter(20);
export const joinAttemptsOverall = limiter(600);
export const roomCreations = limiter(20);
export function resetRateLimits() {
    joinAttempts.reset();
    joinAttemptsOverall.reset();
    roomCreations.reset();
}
