import { init_session_key, parseSessionKey } from "../../../src/routing/session-key.js";
//#region extensions/weixin/src/delivery-to.ts
init_session_key();
/**
* Resolves Weixin ilink `chat_id` and optional `accountId` from cron / UI `delivery.to`.
*/
function normalizeWeixinCronDeliveryTo(to) {
	const trimmed = to.trim();
	if (!trimmed) return { chatId: trimmed };
	const parsed = parseSessionKey(trimmed);
	if (parsed?.source === "weixin" && (parsed.peerKind === "direct" || parsed.peerKind === "dm") && parsed.peerId) {
		const accountId = parsed.accountId && parsed.accountId !== "_" ? parsed.accountId : void 0;
		return {
			chatId: parsed.peerId,
			accountId
		};
	}
	const parts = trimmed.split(":");
	if (parts.length === 3 && parts[1]?.toLowerCase() === "direct" && parts[0] && parts[2]) return {
		chatId: parts[2],
		accountId: parts[0]
	};
	return { chatId: trimmed };
}
/**
* If exactly one indexed weixin DM session matches `ilinkPeerId`, return that session's accountId.
*/
async function resolveWeixinAccountIdFromSessions(store, ilinkPeerId) {
	const normalized = ilinkPeerId.trim().toLowerCase();
	if (!normalized) return void 0;
	const accountIds = /* @__PURE__ */ new Set();
	let offset = 0;
	const pageSize = 2e3;
	for (;;) {
		const batch = await store.list({
			channel: "weixin",
			limit: pageSize,
			offset
		});
		for (const s of batch.items) if (s.routing?.peerId?.toLowerCase() === normalized && s.routing?.accountId) accountIds.add(s.routing.accountId);
		if (!batch.hasMore) break;
		offset += pageSize;
	}
	if (accountIds.size === 1) return [...accountIds][0];
}
/** Like {@link normalizeWeixinCronDeliveryTo}, plus session-index lookup for bare ilink user ids. */
async function normalizeWeixinCronDeliveryToResolved(to, sessionStore) {
	const base = normalizeWeixinCronDeliveryTo(to);
	if (base.accountId || !sessionStore) return base;
	if (!to.trim().includes(":")) {
		const accountId = await resolveWeixinAccountIdFromSessions(sessionStore, base.chatId);
		if (accountId) return {
			chatId: base.chatId,
			accountId
		};
	}
	return base;
}
//#endregion
export { normalizeWeixinCronDeliveryTo, normalizeWeixinCronDeliveryToResolved, resolveWeixinAccountIdFromSessions };

//# sourceMappingURL=delivery-to.js.map