const require_rolldown_runtime = require('../../../../../../../_virtual/rolldown_runtime.js');
const require_decorate = require('../../../../../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorate.js');
const require_DidCommAttachment = require('../../../../decorators/attachment/DidCommAttachment.js');
const require_DidCommProblemReportError = require('../../../../errors/problem-reports/DidCommProblemReportError.js');
require('../../../../errors/index.js');
const require_DidCommProtocol = require('../../../../models/features/DidCommProtocol.js');
const require_DidCommOutboundMessageContext = require('../../../../models/DidCommOutboundMessageContext.js');
require('../../../../models/index.js');
const require_DidCommEvents = require('../../../../DidCommEvents.js');
const require_DidCommModuleConfig = require('../../../../DidCommModuleConfig.js');
const require_DidCommMessagePickupEvents = require('../../DidCommMessagePickupEvents.js');
const require_DidCommMessagePickupModuleConfig = require('../../DidCommMessagePickupModuleConfig.js');
const require_DidCommMessagePickupSessionService = require('../../services/DidCommMessagePickupSessionService.js');
const require_DidCommBaseMessagePickupProtocol = require('../DidCommBaseMessagePickupProtocol.js');
const require_DidCommRoutingProblemReportReason = require('../../../routing/error/DidCommRoutingProblemReportReason.js');
const require_DidCommMessagePickupSession = require('../../DidCommMessagePickupSession.js');
require('../../services/index.js');
const require_DidCommDeliveryRequestV2Message = require('./messages/DidCommDeliveryRequestV2Message.js');
const require_DidCommLiveDeliveryChangeV2Message = require('./messages/DidCommLiveDeliveryChangeV2Message.js');
const require_DidCommMessageDeliveryV2Message = require('./messages/DidCommMessageDeliveryV2Message.js');
const require_DidCommMessagesReceivedV2Message = require('./messages/DidCommMessagesReceivedV2Message.js');
const require_DidCommStatusV2Message = require('./messages/DidCommStatusV2Message.js');
const require_DidCommStatusRequestV2Message = require('./messages/DidCommStatusRequestV2Message.js');
require('./messages/index.js');
const require_DidCommDeliveryRequestV2Handler = require('./handlers/DidCommDeliveryRequestV2Handler.js');
const require_DidCommLiveDeliveryChangeV2Handler = require('./handlers/DidCommLiveDeliveryChangeV2Handler.js');
const require_DidCommMessageDeliveryV2Handler = require('./handlers/DidCommMessageDeliveryV2Handler.js');
const require_DidCommMessagesReceivedV2Handler = require('./handlers/DidCommMessagesReceivedV2Handler.js');
const require_DidCommStatusV2Handler = require('./handlers/DidCommStatusV2Handler.js');
const require_DidCommStatusRequestV2Handler = require('./handlers/DidCommStatusRequestV2Handler.js');
require('./handlers/index.js');
let __credo_ts_core = require("@credo-ts/core");
__credo_ts_core = require_rolldown_runtime.__toESM(__credo_ts_core);

//#region ../didcomm/src/modules/message-pickup/protocol/v2/DidCommMessagePickupV2Protocol.ts
let DidCommMessagePickupV2Protocol = class DidCommMessagePickupV2Protocol$1 extends require_DidCommBaseMessagePickupProtocol.DidCommBaseMessagePickupProtocol {
	constructor(..._args) {
		super(..._args);
		this.version = "v2";
	}
	/**
	* Registers the protocol implementation (handlers, feature registry) on the agent.
	*/
	register(messageHandlerRegistry, featureRegistry) {
		messageHandlerRegistry.registerMessageHandlers([
			new require_DidCommStatusRequestV2Handler.DidCommStatusRequestV2Handler(this),
			new require_DidCommDeliveryRequestV2Handler.DidCommDeliveryRequestV2Handler(this),
			new require_DidCommMessagesReceivedV2Handler.DidCommMessagesReceivedV2Handler(this),
			new require_DidCommStatusV2Handler.DidCommStatusV2Handler(this),
			new require_DidCommMessageDeliveryV2Handler.DidCommMessageDeliveryV2Handler(this),
			new require_DidCommLiveDeliveryChangeV2Handler.DidCommLiveDeliveryChangeV2Handler(this)
		]);
		featureRegistry.register(new require_DidCommProtocol.DidCommProtocol({
			id: "https://didcomm.org/messagepickup/2.0",
			roles: ["mediator", "recipient"]
		}));
	}
	async createPickupMessage(_agentContext, options) {
		const { connectionRecord, recipientDid: recipientKey } = options;
		connectionRecord.assertReady();
		return { message: new require_DidCommStatusRequestV2Message.DidCommStatusRequestV2Message({ recipientKey }) };
	}
	async createDeliveryMessage(agentContext, options) {
		const { connectionRecord, recipientKey, messages } = options;
		connectionRecord.assertReady();
		const queueTransportRepository = agentContext.dependencyManager.resolve(require_DidCommModuleConfig.DidCommModuleConfig).queueTransportRepository;
		const messagesToDeliver = messages ?? await queueTransportRepository.takeFromQueue(agentContext, {
			connectionId: connectionRecord.id,
			recipientDid: recipientKey,
			limit: 10
		});
		if (messagesToDeliver.length === 0) return;
		return { message: new require_DidCommMessageDeliveryV2Message.DidCommMessageDeliveryV2Message({ attachments: messagesToDeliver.map((msg) => new require_DidCommAttachment.DidCommAttachment({
			id: msg.id,
			lastmodTime: msg.receivedAt,
			data: { json: msg.encryptedMessage }
		})) }) };
	}
	async setLiveDeliveryMode(_agentContext, options) {
		const { connectionRecord, liveDelivery } = options;
		connectionRecord.assertReady();
		return { message: new require_DidCommLiveDeliveryChangeV2Message.DidCommLiveDeliveryChangeV2Message({ liveDelivery }) };
	}
	async processStatusRequest(messageContext) {
		const connection = messageContext.assertReadyConnection();
		const recipientKey = messageContext.message.recipientKey;
		const agentContext = messageContext.agentContext;
		const queueTransportRepository = agentContext.dependencyManager.resolve(require_DidCommModuleConfig.DidCommModuleConfig).queueTransportRepository;
		return new require_DidCommOutboundMessageContext.DidCommOutboundMessageContext(new require_DidCommStatusV2Message.DidCommStatusV2Message({
			threadId: messageContext.message.threadId,
			recipientKey,
			messageCount: await queueTransportRepository.getAvailableMessageCount(agentContext, {
				connectionId: connection.id,
				recipientDid: recipientKey ? (0, __credo_ts_core.verkeyToDidKey)(recipientKey) : void 0
			})
		}), {
			agentContext: messageContext.agentContext,
			connection
		});
	}
	async processDeliveryRequest(messageContext) {
		const connection = messageContext.assertReadyConnection();
		const recipientKey = messageContext.message.recipientKey;
		const { agentContext, message } = messageContext;
		const messages = await agentContext.dependencyManager.resolve(require_DidCommModuleConfig.DidCommModuleConfig).queueTransportRepository.takeFromQueue(agentContext, {
			connectionId: connection.id,
			recipientDid: recipientKey ? (0, __credo_ts_core.verkeyToDidKey)(recipientKey) : void 0,
			limit: message.limit
		});
		const attachments = messages.map((msg) => new require_DidCommAttachment.DidCommAttachment({
			id: msg.id,
			lastmodTime: msg.receivedAt,
			data: { json: msg.encryptedMessage }
		}));
		return new require_DidCommOutboundMessageContext.DidCommOutboundMessageContext(messages.length > 0 ? new require_DidCommMessageDeliveryV2Message.DidCommMessageDeliveryV2Message({
			threadId: messageContext.message.threadId,
			recipientKey,
			attachments
		}) : new require_DidCommStatusV2Message.DidCommStatusV2Message({
			threadId: messageContext.message.threadId,
			recipientKey,
			messageCount: 0
		}), {
			agentContext: messageContext.agentContext,
			connection
		});
	}
	async processMessagesReceived(messageContext) {
		const connection = messageContext.assertReadyConnection();
		const { agentContext, message } = messageContext;
		const queueTransportRepository = agentContext.dependencyManager.resolve(require_DidCommModuleConfig.DidCommModuleConfig).queueTransportRepository;
		if (message.messageIdList.length) await queueTransportRepository.removeMessages(agentContext, {
			connectionId: connection.id,
			messageIds: message.messageIdList
		});
		return new require_DidCommOutboundMessageContext.DidCommOutboundMessageContext(new require_DidCommStatusV2Message.DidCommStatusV2Message({
			threadId: messageContext.message.threadId,
			messageCount: await queueTransportRepository.getAvailableMessageCount(agentContext, { connectionId: connection.id })
		}), {
			agentContext: messageContext.agentContext,
			connection
		});
	}
	async processStatus(messageContext) {
		const { message: statusMessage } = messageContext;
		const { messageCount, recipientKey } = statusMessage;
		const connection = messageContext.assertReadyConnection();
		const messagePickupModuleConfig = messageContext.agentContext.dependencyManager.resolve(require_DidCommMessagePickupModuleConfig.DidCommMessagePickupModuleConfig);
		const eventEmitter = messageContext.agentContext.dependencyManager.resolve(__credo_ts_core.EventEmitter);
		if (messageCount === 0) {
			eventEmitter.emit(messageContext.agentContext, {
				type: require_DidCommMessagePickupEvents.DidCommMessagePickupEventTypes.MessagePickupCompleted,
				payload: {
					connection,
					threadId: statusMessage.threadId
				}
			});
			return null;
		}
		const { maximumBatchSize: maximumMessagePickup } = messagePickupModuleConfig;
		return new require_DidCommDeliveryRequestV2Message.DidCommDeliveryRequestV2Message({
			limit: messageCount < maximumMessagePickup ? messageCount : maximumMessagePickup,
			recipientKey
		});
	}
	async processLiveDeliveryChange(messageContext) {
		const { agentContext, message, sessionId } = messageContext;
		const connection = messageContext.assertReadyConnection();
		const queueTransportRepository = agentContext.dependencyManager.resolve(require_DidCommModuleConfig.DidCommModuleConfig).queueTransportRepository;
		const sessionService = messageContext.agentContext.dependencyManager.resolve(require_DidCommMessagePickupSessionService.DidCommMessagePickupSessionService);
		if (message.liveDelivery && sessionId) sessionService.saveLiveSession(agentContext, {
			connectionId: connection.id,
			protocolVersion: "v2",
			role: require_DidCommMessagePickupSession.DidCommMessagePickupSessionRole.MessageHolder,
			transportSessionId: sessionId
		});
		else sessionService.removeLiveSession(agentContext, { connectionId: connection.id });
		return new require_DidCommOutboundMessageContext.DidCommOutboundMessageContext(new require_DidCommStatusV2Message.DidCommStatusV2Message({
			threadId: message.threadId,
			liveDelivery: message.liveDelivery,
			messageCount: await queueTransportRepository.getAvailableMessageCount(agentContext, { connectionId: connection.id })
		}), {
			agentContext: messageContext.agentContext,
			connection
		});
	}
	async processDelivery(messageContext) {
		messageContext.assertReadyConnection();
		const { appendedAttachments } = messageContext.message;
		const eventEmitter = messageContext.agentContext.dependencyManager.resolve(__credo_ts_core.EventEmitter);
		if (!appendedAttachments) throw new require_DidCommProblemReportError.DidCommProblemReportError("Error processing attachments", { problemCode: require_DidCommRoutingProblemReportReason.DidCommRoutingProblemReportReason.ErrorProcessingAttachments });
		const ids = [];
		for (const attachment of appendedAttachments) {
			ids.push(attachment.id);
			eventEmitter.emit(messageContext.agentContext, {
				type: require_DidCommEvents.DidCommEventTypes.DidCommMessageReceived,
				payload: {
					message: attachment.getDataAsJson(),
					contextCorrelationId: messageContext.agentContext.contextCorrelationId,
					receivedAt: attachment.lastmodTime
				}
			});
		}
		return new require_DidCommMessagesReceivedV2Message.DidCommMessagesReceivedV2Message({ messageIdList: ids });
	}
};
DidCommMessagePickupV2Protocol = require_decorate.__decorate([(0, __credo_ts_core.injectable)()], DidCommMessagePickupV2Protocol);

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