import { n as confirmSettlement, p as InvalidKeyComponentError } from "../src-BedZtlrm.js";
//#region src/subscriptions/ingest.ts
const MAX_AMOUNT_MINOR_DIGITS = 21;
function validateKeyComponent(value, field) {
	if (typeof value !== "string" || value.trim() === "") throw new InvalidKeyComponentError(`subscription chargeKey component "${field}" must be non-empty`, {
		field,
		value: String(value)
	});
	if (value.includes(":")) throw new InvalidKeyComponentError(`subscription chargeKey component "${field}" must not contain ":"`, {
		field,
		value
	});
	return value;
}
function buildChargeKey(subscriptionId, period) {
	validateKeyComponent(subscriptionId, "subscriptionId");
	validateKeyComponent(period, "period");
	return `${subscriptionId}:${period}`;
}
function amountMinorToNumber(amountMinor) {
	if (amountMinor.toString().replace("-", "").length > MAX_AMOUNT_MINOR_DIGITS) throw new Error(`subscription settlement amountMinor has too many digits, got ${amountMinor}`);
	if (amountMinor < 0n) throw new Error(`subscription settlement amountMinor must be non-negative, got ${amountMinor}`);
	if (amountMinor > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`subscription settlement amountMinor exceeds Number.MAX_SAFE_INTEGER, got ${amountMinor}`);
	return Number(amountMinor);
}
async function ingestWebhook(deps, rawEvent) {
	const parsed = await deps.provider.parseWebhook(rawEvent);
	if (parsed.kind === "other") return {
		eventId: parsed.eventId ?? "subscription:other",
		kind: "other",
		raw: parsed.raw
	};
	const chargeKey = buildChargeKey(parsed.subscriptionId, parsed.period);
	const amount = amountMinorToNumber(parsed.amountMinor);
	await confirmSettlement(chargeKey, {
		amount,
		currency: parsed.currency,
		providerRef: parsed.subscriptionId
	}, deps);
	return {
		eventId: parsed.eventId ?? chargeKey,
		kind: "settlement",
		chargeKey,
		providerRef: parsed.subscriptionId,
		amount,
		currency: parsed.currency,
		subscriptionId: parsed.subscriptionId,
		period: parsed.period,
		amountMinor: parsed.amountMinor
	};
}
//#endregion
export { buildChargeKey, ingestWebhook };
