import { getKeydbClient } from "~/utils/keydb";

const keydb = getKeydbClient();
interface RateLimiterConfig {
	windowSize: number;
	maxRequests: number;
	analytics: boolean;
}
/**
 * @description The rate limiter class
 * @param windowSize The window size in seconds
 * @param maxRequests The maximum number of requests
 * @param analytics Whether to log analytics
 */
export class RateLimiterHandler {
	private config: RateLimiterConfig;

	constructor(config: RateLimiterConfig) {
		this.config = config;
	}
	/**
	 * @description Limit the number of requests for a given key
	 * @param key The key to limit, "event_identifier" is recommended
	 */
	async limit(key: string): Promise<{ success: boolean }> {
		if (!keydb) {
			console.warn("KeyDB client is not initialized. Skipping rate limiting.");
			return { success: true };
		}
		const redisKey = `ratelimiter:${key}`;
		const { windowSize, maxRequests, analytics } = this.config;
		// Increment the count atomically
		const count = await keydb.incr(redisKey);

		if (count === 1) {
			// First request, set expiry
			await keydb.expire(redisKey, windowSize);
			if (analytics) {
				console.log(`New Ratelimiter key: ${key} created.`);
			}
		}
		if (count > maxRequests) {
			if (analytics) {
				console.error(
					`Rate limit exceeded for key: ${key}. Current count: ${count}, Max allowed: ${maxRequests}`,
				);
			}
			return { success: false };
		}
		return { success: true };
	}
}
