import { upsertPairingRequestSync } from "./pairing-store.js";
import { buildPairingInstructionText } from "./pairing-messages.js";
import { broadcastPairingEvent } from "./pairing-events.js";
//#region src/channels/pairing/pairing-challenge.ts
/**
* OpenClaw-style pairing: mint or refresh a pending code; notify the user only on new codes.
* Repeat DMs refresh lastSeenAt and broadcast SSE without re-sending the bot message.
*/
async function issuePairingChallenge(params) {
	const normalizedAccountId = params.accountId.trim().toLowerCase() || "default";
	const { code, created } = upsertPairingRequestSync({
		pairingFilePath: params.pairingFilePath,
		id: params.senderId,
		accountId: params.accountId,
		meta: params.meta
	});
	const broadcastPayload = {
		channel: params.channel,
		accountId: normalizedAccountId,
		senderId: params.senderId
	};
	if (!created) {
		if (code) broadcastPairingEvent("channels.pairing.refreshed", broadcastPayload);
		return {
			created: false,
			code: code || void 0
		};
	}
	if (!code) return { created: false };
	params.onCreated?.({ code });
	broadcastPairingEvent("channels.pairing.requested", broadcastPayload);
	const replyText = params.buildReplyText?.({
		code,
		senderIdLine: params.senderIdLine
	}) ?? buildPairingInstructionText({
		channel: params.channel,
		accountId: params.accountId,
		code,
		senderIdLine: params.senderIdLine
	});
	try {
		await params.sendPairingReply(replyText);
	} catch (err) {
		params.onReplyError?.(err);
	}
	return {
		created: true,
		code
	};
}
//#endregion
export { issuePairingChallenge };

//# sourceMappingURL=pairing-challenge.js.map