const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.js');
const require_decorateMetadata = require('../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorateMetadata.js');
const require_decorate = require('../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorate.js');
const require_messageType = require('./util/messageType.js');
const require_DidCommProblemReportMessage = require('./messages/problem-reports/DidCommProblemReportMessage.js');
const require_DidCommProblemReportError = require('./errors/problem-reports/DidCommProblemReportError.js');
require('./errors/problem-reports/index.js');
const require_DidCommMessageHandlerMiddleware = require('./handlers/DidCommMessageHandlerMiddleware.js');
require('./messages/index.js');
const require_DidCommProblemReportReason = require('./models/problem-reports/DidCommProblemReportReason.js');
const require_DidCommOutboundMessageContext = require('./models/DidCommOutboundMessageContext.js');
require('./models/index.js');
const require_DidCommEvents = require('./DidCommEvents.js');
const require_decorateParam = require('../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorateParam.js');
const require_DidCommMessageSender = require('./DidCommMessageSender.js');
const require_DidCommMessageHandlerRegistry = require('./DidCommMessageHandlerRegistry.js');
let __credo_ts_core = require("@credo-ts/core");
__credo_ts_core = require_rolldown_runtime.__toESM(__credo_ts_core);

//#region ../didcomm/src/DidCommDispatcher.ts
var _ref, _ref2, _ref3;
let DidCommDispatcher = class DidCommDispatcher$1 {
	constructor(messageSender, eventEmitter, messageHandlerRegistry, logger) {
		this.defaultHandlerMiddleware = async (inboundMessageContext, next) => {
			let messageHandler = inboundMessageContext.messageHandler;
			const fallbackMessageHandler = inboundMessageContext.agentContext.dependencyManager.resolve(require_DidCommMessageHandlerRegistry.DidCommMessageHandlerRegistry).fallbackMessageHandler;
			if (!messageHandler && fallbackMessageHandler) messageHandler = {
				supportedMessages: [],
				handle: fallbackMessageHandler
			};
			if (!messageHandler) throw new require_DidCommProblemReportError.DidCommProblemReportError(`Error handling message ${inboundMessageContext.message.id} with type ${inboundMessageContext.message.type}. The message type is not supported`, { problemCode: require_DidCommProblemReportReason.DidCommProblemReportReason.MessageParseFailure });
			const outboundMessage = await messageHandler.handle(inboundMessageContext);
			if (outboundMessage) inboundMessageContext.setResponseMessage(outboundMessage);
			await next();
		};
		this.messageSender = messageSender;
		this.eventEmitter = eventEmitter;
		this.messageHandlerRegistry = messageHandlerRegistry;
		this.logger = logger;
	}
	async dispatch(messageContext) {
		const { agentContext, connection, senderKey, recipientKey, message, encryptedMessage } = messageContext;
		const messageHandler = this.messageHandlerRegistry.getHandlerForMessageType(message.type);
		if (messageHandler) messageContext.setMessageHandler(messageHandler);
		let outboundMessage;
		try {
			const middlewares = [...agentContext.dependencyManager.resolve(require_DidCommMessageHandlerRegistry.DidCommMessageHandlerRegistry).messageHandlerMiddlewares, this.defaultHandlerMiddleware];
			await require_DidCommMessageHandlerMiddleware.DidCommMessageHandlerMiddlewareRunner.run(middlewares, messageContext);
			outboundMessage = messageContext.responseMessage;
		} catch (error) {
			const problemReportMessage = error.problemReport;
			if (problemReportMessage instanceof require_DidCommProblemReportMessage.DidCommProblemReportMessage && messageContext.connection) {
				if (require_messageType.canHandleMessageType(require_DidCommProblemReportMessage.DidCommProblemReportMessage, require_messageType.parseMessageType(messageContext.message.type))) throw new __credo_ts_core.CredoError(`Not sending problem report in response to problem report: ${message}`);
				const { protocolUri: problemReportProtocolUri } = require_messageType.parseMessageType(problemReportMessage.type);
				const { protocolUri: inboundProtocolUri } = require_messageType.parseMessageType(messageContext.message.type);
				if (inboundProtocolUri === problemReportProtocolUri) problemReportMessage.setThread({ threadId: message.threadId });
				else problemReportMessage.setThread({ parentThreadId: message.id });
				outboundMessage = new require_DidCommOutboundMessageContext.DidCommOutboundMessageContext(problemReportMessage, {
					agentContext,
					connection: messageContext.connection,
					inboundMessageContext: messageContext
				});
			} else {
				this.logger.error(`Error handling message with type ${message.type}`, {
					message: message.toJSON(),
					error,
					senderKey: senderKey?.fingerprint,
					recipientKey: recipientKey?.fingerprint,
					connectionId: connection?.id
				});
				throw error;
			}
		}
		if (outboundMessage) {
			if (!outboundMessage.inboundMessageContext) outboundMessage.inboundMessageContext = messageContext;
			await this.messageSender.sendMessage(outboundMessage);
		}
		this.eventEmitter.emit(agentContext, {
			type: require_DidCommEvents.DidCommEventTypes.DidCommMessageProcessed,
			payload: {
				message,
				connection,
				receivedAt: messageContext.receivedAt,
				encryptedMessage
			}
		});
	}
};
DidCommDispatcher = require_decorate.__decorate([
	(0, __credo_ts_core.injectable)(),
	require_decorateParam.__decorateParam(3, (0, __credo_ts_core.inject)(__credo_ts_core.InjectionSymbols.Logger)),
	require_decorateMetadata.__decorateMetadata("design:paramtypes", [
		typeof (_ref = typeof require_DidCommMessageSender.DidCommMessageSender !== "undefined" && require_DidCommMessageSender.DidCommMessageSender) === "function" ? _ref : Object,
		typeof (_ref2 = typeof __credo_ts_core.EventEmitter !== "undefined" && __credo_ts_core.EventEmitter) === "function" ? _ref2 : Object,
		typeof (_ref3 = typeof require_DidCommMessageHandlerRegistry.DidCommMessageHandlerRegistry !== "undefined" && require_DidCommMessageHandlerRegistry.DidCommMessageHandlerRegistry) === "function" ? _ref3 : Object,
		Object
	])
], DidCommDispatcher);

//#endregion
Object.defineProperty(exports, 'DidCommDispatcher', {
  enumerable: true,
  get: function () {
    return DidCommDispatcher;
  }
});