import { __decorate } from "../../../../../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorate.mjs";
import { DidCommAttachment } from "../../../../decorators/attachment/DidCommAttachment.mjs";
import { DidCommProblemReportError } from "../../../../errors/problem-reports/DidCommProblemReportError.mjs";
import "../../../../errors/index.mjs";
import { DidCommProtocol } from "../../../../models/features/DidCommProtocol.mjs";
import { DidCommOutboundMessageContext } from "../../../../models/DidCommOutboundMessageContext.mjs";
import "../../../../models/index.mjs";
import { DidCommEventTypes } from "../../../../DidCommEvents.mjs";
import { DidCommModuleConfig } from "../../../../DidCommModuleConfig.mjs";
import { DidCommMessagePickupEventTypes } from "../../DidCommMessagePickupEvents.mjs";
import { DidCommMessagePickupModuleConfig } from "../../DidCommMessagePickupModuleConfig.mjs";
import { DidCommMessagePickupSessionService } from "../../services/DidCommMessagePickupSessionService.mjs";
import { DidCommBaseMessagePickupProtocol } from "../DidCommBaseMessagePickupProtocol.mjs";
import { DidCommRoutingProblemReportReason } from "../../../routing/error/DidCommRoutingProblemReportReason.mjs";
import { DidCommMessagePickupSessionRole } from "../../DidCommMessagePickupSession.mjs";
import "../../services/index.mjs";
import { DidCommDeliveryRequestV2Message } from "./messages/DidCommDeliveryRequestV2Message.mjs";
import { DidCommLiveDeliveryChangeV2Message } from "./messages/DidCommLiveDeliveryChangeV2Message.mjs";
import { DidCommMessageDeliveryV2Message } from "./messages/DidCommMessageDeliveryV2Message.mjs";
import { DidCommMessagesReceivedV2Message } from "./messages/DidCommMessagesReceivedV2Message.mjs";
import { DidCommStatusV2Message } from "./messages/DidCommStatusV2Message.mjs";
import { DidCommStatusRequestV2Message } from "./messages/DidCommStatusRequestV2Message.mjs";
import "./messages/index.mjs";
import { DidCommDeliveryRequestV2Handler } from "./handlers/DidCommDeliveryRequestV2Handler.mjs";
import { DidCommLiveDeliveryChangeV2Handler } from "./handlers/DidCommLiveDeliveryChangeV2Handler.mjs";
import { DidCommMessageDeliveryV2Handler } from "./handlers/DidCommMessageDeliveryV2Handler.mjs";
import { DidCommMessagesReceivedV2Handler } from "./handlers/DidCommMessagesReceivedV2Handler.mjs";
import { DidCommStatusV2Handler } from "./handlers/DidCommStatusV2Handler.mjs";
import { DidCommStatusRequestV2Handler } from "./handlers/DidCommStatusRequestV2Handler.mjs";
import "./handlers/index.mjs";
import { EventEmitter, injectable, verkeyToDidKey } from "@credo-ts/core";

//#region ../didcomm/src/modules/message-pickup/protocol/v2/DidCommMessagePickupV2Protocol.ts
let DidCommMessagePickupV2Protocol = class DidCommMessagePickupV2Protocol$1 extends DidCommBaseMessagePickupProtocol {
	constructor(..._args) {
		super(..._args);
		this.version = "v2";
	}
	/**
	* Registers the protocol implementation (handlers, feature registry) on the agent.
	*/
	register(messageHandlerRegistry, featureRegistry) {
		messageHandlerRegistry.registerMessageHandlers([
			new DidCommStatusRequestV2Handler(this),
			new DidCommDeliveryRequestV2Handler(this),
			new DidCommMessagesReceivedV2Handler(this),
			new DidCommStatusV2Handler(this),
			new DidCommMessageDeliveryV2Handler(this),
			new DidCommLiveDeliveryChangeV2Handler(this)
		]);
		featureRegistry.register(new 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 DidCommStatusRequestV2Message({ recipientKey }) };
	}
	async createDeliveryMessage(agentContext, options) {
		const { connectionRecord, recipientKey, messages } = options;
		connectionRecord.assertReady();
		const queueTransportRepository = agentContext.dependencyManager.resolve(DidCommModuleConfig).queueTransportRepository;
		const messagesToDeliver = messages ?? await queueTransportRepository.takeFromQueue(agentContext, {
			connectionId: connectionRecord.id,
			recipientDid: recipientKey,
			limit: 10
		});
		if (messagesToDeliver.length === 0) return;
		return { message: new DidCommMessageDeliveryV2Message({ attachments: messagesToDeliver.map((msg) => new DidCommAttachment({
			id: msg.id,
			lastmodTime: msg.receivedAt,
			data: { json: msg.encryptedMessage }
		})) }) };
	}
	async setLiveDeliveryMode(_agentContext, options) {
		const { connectionRecord, liveDelivery } = options;
		connectionRecord.assertReady();
		return { message: new DidCommLiveDeliveryChangeV2Message({ liveDelivery }) };
	}
	async processStatusRequest(messageContext) {
		const connection = messageContext.assertReadyConnection();
		const recipientKey = messageContext.message.recipientKey;
		const agentContext = messageContext.agentContext;
		const queueTransportRepository = agentContext.dependencyManager.resolve(DidCommModuleConfig).queueTransportRepository;
		return new DidCommOutboundMessageContext(new DidCommStatusV2Message({
			threadId: messageContext.message.threadId,
			recipientKey,
			messageCount: await queueTransportRepository.getAvailableMessageCount(agentContext, {
				connectionId: connection.id,
				recipientDid: recipientKey ? 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(DidCommModuleConfig).queueTransportRepository.takeFromQueue(agentContext, {
			connectionId: connection.id,
			recipientDid: recipientKey ? verkeyToDidKey(recipientKey) : void 0,
			limit: message.limit
		});
		const attachments = messages.map((msg) => new DidCommAttachment({
			id: msg.id,
			lastmodTime: msg.receivedAt,
			data: { json: msg.encryptedMessage }
		}));
		return new DidCommOutboundMessageContext(messages.length > 0 ? new DidCommMessageDeliveryV2Message({
			threadId: messageContext.message.threadId,
			recipientKey,
			attachments
		}) : new 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(DidCommModuleConfig).queueTransportRepository;
		if (message.messageIdList.length) await queueTransportRepository.removeMessages(agentContext, {
			connectionId: connection.id,
			messageIds: message.messageIdList
		});
		return new DidCommOutboundMessageContext(new 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(DidCommMessagePickupModuleConfig);
		const eventEmitter = messageContext.agentContext.dependencyManager.resolve(EventEmitter);
		if (messageCount === 0) {
			eventEmitter.emit(messageContext.agentContext, {
				type: DidCommMessagePickupEventTypes.MessagePickupCompleted,
				payload: {
					connection,
					threadId: statusMessage.threadId
				}
			});
			return null;
		}
		const { maximumBatchSize: maximumMessagePickup } = messagePickupModuleConfig;
		return new DidCommDeliveryRequestV2Message({
			limit: messageCount < maximumMessagePickup ? messageCount : maximumMessagePickup,
			recipientKey
		});
	}
	async processLiveDeliveryChange(messageContext) {
		const { agentContext, message, sessionId } = messageContext;
		const connection = messageContext.assertReadyConnection();
		const queueTransportRepository = agentContext.dependencyManager.resolve(DidCommModuleConfig).queueTransportRepository;
		const sessionService = messageContext.agentContext.dependencyManager.resolve(DidCommMessagePickupSessionService);
		if (message.liveDelivery && sessionId) sessionService.saveLiveSession(agentContext, {
			connectionId: connection.id,
			protocolVersion: "v2",
			role: DidCommMessagePickupSessionRole.MessageHolder,
			transportSessionId: sessionId
		});
		else sessionService.removeLiveSession(agentContext, { connectionId: connection.id });
		return new DidCommOutboundMessageContext(new 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(EventEmitter);
		if (!appendedAttachments) throw new DidCommProblemReportError("Error processing attachments", { problemCode: DidCommRoutingProblemReportReason.ErrorProcessingAttachments });
		const ids = [];
		for (const attachment of appendedAttachments) {
			ids.push(attachment.id);
			eventEmitter.emit(messageContext.agentContext, {
				type: DidCommEventTypes.DidCommMessageReceived,
				payload: {
					message: attachment.getDataAsJson(),
					contextCorrelationId: messageContext.agentContext.contextCorrelationId,
					receivedAt: attachment.lastmodTime
				}
			});
		}
		return new DidCommMessagesReceivedV2Message({ messageIdList: ids });
	}
};
DidCommMessagePickupV2Protocol = __decorate([injectable()], DidCommMessagePickupV2Protocol);

//#endregion
export { DidCommMessagePickupV2Protocol };
//# sourceMappingURL=DidCommMessagePickupV2Protocol.mjs.map