import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { resolveClientIpFromRequest } from "../../client-ip.js";
import { getClientIpFromHeaders } from "../../security/loopback.js";
import { createMiddleware } from "hono/factory";
import { getConnInfo } from "@hono/node-server/conninfo";
//#region src/gateway/hono/middleware/logger.ts
init_logger();
const log = createLogger("Hono:Request");
function resolveRemoteAddress(c) {
	try {
		return getConnInfo(c).remote.address;
	} catch {
		return;
	}
}
function resolveRequestClientIp(c, config) {
	const trustedProxies = config?.trustedProxies;
	if (trustedProxies?.length) return resolveClientIpFromRequest({
		remoteAddress: resolveRemoteAddress(c),
		getHeader: (name) => c.req.header(name),
		trustedProxies,
		allowRealIpFallback: config?.allowRealIpFallback
	});
	return getClientIpFromHeaders({ get: (name) => c.req.header(name) ?? void 0 });
}
function logger(config) {
	return createMiddleware(async (c, next) => {
		const start = Date.now();
		const clientIp = resolveRequestClientIp(c, config);
		const userAgent = c.req.header("user-agent") ?? void 0;
		const contentLength = c.req.header("content-length");
		const referer = c.req.header("referer") ?? void 0;
		await next();
		const duration = Date.now() - start;
		const status = c.res.status;
		const isServerError = status >= 500;
		const isClientError = status >= 400 && status < 500;
		const isSlow = duration > 1e3;
		const logData = {
			method: c.req.method,
			path: c.req.path,
			status,
			durationMs: duration,
			clientIp,
			...userAgent ? { userAgent } : {},
			...contentLength ? { contentLength: Number(contentLength) } : {},
			...referer ? { referer } : {}
		};
		const msg = `HTTP ${c.req.method} ${c.req.path} → ${status} (${duration}ms)`;
		if (isServerError || isSlow) log.warn(logData, msg);
		else if (isClientError) log.info(logData, msg);
		else log.debug(logData, msg);
	});
}
//#endregion
export { logger };

//# sourceMappingURL=logger.js.map