import { baseLogger as logger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { randomBytes } from "crypto";
//#region src/agent/middleware/context.ts
/**
* Request-scoped context for structured logging fields (requestId, sessionId, userId, …).
*
* Wire `onRequest` / `onResponse` around a handling scope; use `getContext` with
* `logger.withContext` when you need request fields on log lines.
*
*   import { ContextMiddleware } from './middleware/index.js';
*/
init_logger();
const log = logger.child({ module: "ContextMiddleware" });
var ContextMiddleware = class {
	currentContext = {};
	contextDepth = 0;
	generateRequestId() {
		return `req_${Date.now().toString(36)}_${randomBytes(4).toString("hex")}`;
	}
	extractSessionId(sessionKey) {
		return sessionKey.split(":").slice(0, 2).join(":");
	}
	onRequest(context) {
		this.contextDepth++;
		const requestId = this.generateRequestId();
		this.currentContext = {
			requestId,
			sessionId: this.extractSessionId(context.sessionKey),
			userId: context.userId,
			module: context.channel,
			service: "xopc",
			...context.metadata
		};
		log.debug({
			requestId,
			sessionId: this.currentContext.sessionId,
			userId: context.userId,
			depth: this.contextDepth
		}, "Request context started");
		return requestId;
	}
	onResponse() {
		this.contextDepth--;
		if (this.contextDepth <= 0) {
			this.currentContext = {};
			this.contextDepth = 0;
		}
		log.debug({ depth: this.contextDepth }, "Request context ended");
	}
	getContext() {
		return { ...this.currentContext };
	}
	getRequestId() {
		return this.currentContext.requestId;
	}
	extendContext(fields) {
		this.currentContext = {
			...this.currentContext,
			...fields
		};
	}
};
//#endregion
export { ContextMiddleware };

//# sourceMappingURL=context.js.map