/**
 * Simple in-memory rate limiter for auth endpoints.
 * Uses a Map with TTL-based cleanup.
 */

interface RateLimitEntry {
	count: number;
	resetAt: number;
}

const store = new Map<string, RateLimitEntry>();

// Cleanup stale entries periodically
let cleanupInterval: ReturnType<typeof setInterval> | null = null;

function ensureCleanup() {
	if (cleanupInterval) return;
	cleanupInterval = setInterval(() => {
		const now = Date.now();
		for (const [key, entry] of store) {
			if (now > entry.resetAt) {
				store.delete(key);
			}
		}
		// Stop interval if store is empty
		if (store.size === 0 && cleanupInterval) {
			clearInterval(cleanupInterval);
			cleanupInterval = null;
		}
	}, 60_000); // Clean up every minute
}

/**
 * Check if a request is allowed under the rate limit.
 * @param key - Unique identifier (e.g., IP address, email, or combination)
 * @param maxAttempts - Maximum attempts allowed within the window
 * @param windowMs - Time window in milliseconds
 * @returns Object with `allowed` boolean and optional `retryAfterMs`
 */
export function checkRateLimit(
	key: string,
	maxAttempts: number,
	windowMs: number
): { allowed: boolean; retryAfterMs?: number } {
	ensureCleanup();
	const now = Date.now();
	const entry = store.get(key);

	// No existing entry or expired — allow and create new entry
	if (!entry || now > entry.resetAt) {
		store.set(key, { count: 1, resetAt: now + windowMs });
		return { allowed: true };
	}

	// Within window — check count
	if (entry.count < maxAttempts) {
		entry.count++;
		return { allowed: true };
	}

	// Rate limited
	return {
		allowed: false,
		retryAfterMs: entry.resetAt - now
	};
}

/**
 * Reset rate limit for a key (e.g., after successful login)
 */
export function resetRateLimit(key: string): void {
	store.delete(key);
}
