import { ErrorHandler } from "./errors/ErrorHandler.mjs";

//#region src/utils/rateLimiter.ts
const normalizeIP = (ip) => {
	if (!ip) return "unknown";
	if (ip.startsWith("::ffff:")) return ip.substring(7);
	return ip;
};
const ipLimiter = {
	max: 500,
	timeWindow: 60 * 1e3,
	enableDraftSpec: true,
	keyGenerator: (request) => {
		const ip = request.ip ?? request.socket?.remoteAddress ?? request.headers["x-forwarded-for"] ?? "unknown";
		return normalizeIP(typeof ip === "string" ? ip : ip[0]);
	},
	errorResponseBuilder: (_request, context) => {
		const retryAfter = Math.ceil(context.ttl / 1e3);
		const errorResponse = ErrorHandler.formatGenericErrorResponse("RATE_LIMIT_EXCEEDED", {
			limit: `${context.max} per minute`,
			retryAfter
		});
		return {
			statusCode: errorResponse.status,
			...errorResponse
		};
	}
};
const unauthenticatedChatBotLimiter = {
	max: 3,
	timeWindow: 3600 * 1e3,
	enableDraftSpec: true,
	allowList: (request) => {
		return Boolean(request.locals?.user);
	},
	keyGenerator: (request) => {
		const ip = request.ip ?? request.socket?.remoteAddress ?? request.headers["x-forwarded-for"] ?? "unknown";
		return normalizeIP(typeof ip === "string" ? ip : ip[0]);
	},
	errorResponseBuilder: (_request, context) => {
		const retryAfter = Math.ceil(context.ttl / 1e3);
		const errorResponse = ErrorHandler.formatGenericErrorResponse("RATE_LIMIT_EXCEEDED_UNAUTHENTICATED", {
			limit: `${context.max} per hour`,
			retryAfter
		});
		return {
			statusCode: errorResponse.status,
			...errorResponse
		};
	}
};

//#endregion
export { ipLimiter, unauthenticatedChatBotLimiter };
//# sourceMappingURL=rateLimiter.mjs.map