/**
 * Flow Service integration — deposits order revenue into the TBFF flow
 * for automatic threshold-based splits (provider / creator / community).
 */

const FLOW_SERVICE_URL = process.env.FLOW_SERVICE_URL || "http://payment-flow:3010";
const FLOW_ID = process.env.FLOW_ID || "";
const FUNNEL_ID = process.env.FUNNEL_ID || "";

function toUsdcUnits(dollars: number | string): string {
	const d = typeof dollars === "string" ? parseFloat(dollars) : dollars;
	return Math.round(d * 1e6).toString();
}

export async function depositOrderRevenue(
	totalPrice: number | string,
	orderId: string
): Promise<void> {
	if (!FLOW_ID || !FUNNEL_ID) return;

	const amount = toUsdcUnits(totalPrice);
	const url = `${FLOW_SERVICE_URL}/api/flows/${FLOW_ID}/deposit`;

	try {
		const resp = await fetch(url, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ funnelId: FUNNEL_ID, amount, source: "wallet" }),
		});

		if (resp.ok) {
			const data = await resp.json() as { transaction?: { id?: string } };
			console.log(`[Cart] Flow deposit OK: order=${orderId} amount=${amount} tx=${data.transaction?.id}`);
		} else {
			const text = await resp.text();
			console.error(`[Cart] Flow deposit failed (${resp.status}): ${text}`);
		}
	} catch (err) {
		console.error("[Cart] Flow deposit error:", err instanceof Error ? err.message : err);
	}
}
