import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { resolveClientIpFromRequest } from "../../client-ip.js";
import { buckets } from "../../rate-limit/buckets.js";
import { getClientIpFromHeaders } from "../../security/loopback.js";
import "../../rate-limit/index.js";
import { createMiddleware } from "hono/factory";
import { getConnInfo } from "@hono/node-server/conninfo";
//#region src/gateway/hono/middleware/strict-rate-limit.ts
/**
* Per-client request-rate gate for sensitive admin/mutation endpoints.
* Backed by `buckets.strictApi()` — see {@link ../../rate-limit/buckets.ts}.
*/
init_logger();
const log = createLogger("Hono:StrictRateLimit");
function resolveClientIp(c, deps) {
	const { trustedProxies, allowRealIpFallback } = deps.getTrustedProxyContext();
	if (trustedProxies?.length) {
		let remoteAddress;
		try {
			remoteAddress = getConnInfo(c).remote.address;
		} catch {
			remoteAddress = void 0;
		}
		return resolveClientIpFromRequest({
			remoteAddress,
			getHeader: (name) => c.req.header(name),
			trustedProxies,
			allowRealIpFallback
		});
	}
	return getClientIpFromHeaders({ get: (name) => c.req.header(name) ?? void 0 });
}
function createStrictRateLimitMiddleware(deps) {
	return createMiddleware(async (c, next) => {
		const limiter = buckets.strictApi();
		const clientIp = resolveClientIp(c, deps);
		const result = limiter.consume(clientIp);
		if (!result.allowed) {
			const retryAfterSec = Math.ceil(result.retryAfterMs / 1e3);
			log.warn({
				clientIp,
				path: c.req.path,
				method: c.req.method,
				retryAfterSec,
				reason: "strict_rate_limit_exceeded"
			}, "Strict API rate limit exceeded");
			c.header("Retry-After", String(retryAfterSec));
			c.header("X-RateLimit-Remaining", "0");
			return c.json({
				error: "Too many requests",
				code: "rate_limited"
			}, 429);
		}
		c.header("X-RateLimit-Remaining", String(result.remaining));
		await next();
	});
}
//#endregion
export { createStrictRateLimitMiddleware };

//# sourceMappingURL=strict-rate-limit.js.map