import { n as MixedCurrencyError } from "./errors-DXMuB65Y.js";
//#region src/testing.ts
function cloneCart(cart) {
	return {
		id: cart.id,
		currency: cart.currency,
		lines: cart.lines.map((line) => ({
			...line,
			price: { ...line.price }
		})),
		subtotal: cart.subtotal
	};
}
function computeSubtotal(lines) {
	return lines.reduce((sum, line) => sum + line.price.amount * BigInt(line.qty), 0n);
}
function assertMergeCurrency(guest, user) {
	const guestCurrency = guest.lines.length > 0 ? guest.currency : "";
	const userCurrency = user.lines.length > 0 ? user.currency : "";
	if (guestCurrency !== "" && userCurrency !== "" && guestCurrency !== userCurrency) throw new MixedCurrencyError(userCurrency, guestCurrency);
}
function mergeLines(userLines, guestLines) {
	const merged = userLines.map((line) => ({
		...line,
		price: { ...line.price }
	}));
	const indexByVariant = new Map(merged.map((line, index) => [line.variantId, index]));
	for (const guestLine of guestLines) {
		const existingIndex = indexByVariant.get(guestLine.variantId);
		if (existingIndex === void 0) {
			indexByVariant.set(guestLine.variantId, merged.length);
			merged.push({
				...guestLine,
				price: { ...guestLine.price }
			});
			continue;
		}
		const existing = merged[existingIndex];
		merged[existingIndex] = {
			...existing,
			qty: existing.qty + guestLine.qty,
			price: { ...existing.price }
		};
	}
	return merged;
}
function createMemoryCartStore() {
	const carts = /* @__PURE__ */ new Map();
	return {
		async load(cartId) {
			const cart = carts.get(cartId);
			return cart ? cloneCart(cart) : null;
		},
		async save(cart) {
			carts.set(cart.id, cloneCart(cart));
		},
		async merge(guestCartId, userId) {
			const guest = await this.load(guestCartId) ?? {
				id: guestCartId,
				currency: "",
				lines: [],
				subtotal: 0n
			};
			const user = await this.load(userId) ?? {
				id: userId,
				currency: "",
				lines: [],
				subtotal: 0n
			};
			assertMergeCurrency(guest, user);
			const currency = user.lines.length > 0 ? user.currency : guest.lines.length > 0 ? guest.currency : "";
			const lines = mergeLines(user.lines, guest.lines);
			const merged = {
				id: userId,
				currency,
				lines,
				subtotal: computeSubtotal(lines)
			};
			await this.save(merged);
			carts.delete(guestCartId);
			return cloneCart(merged);
		}
	};
}
//#endregion
export { createMemoryCartStore };
