import type { Output } from "../types";
import { formatValue } from "./formatValue";

// getting slippage adjusted minimum output amount for auto routes
export function getAutoMinOutput(output: Output, slippage: number) {
	const PRECISION = 1000000;

	const amount = BigInt(output.amount);
	const scaledSlippage = BigInt(Math.round(slippage * PRECISION));

	const slippageAdjustedAmount =
		amount - (amount * scaledSlippage) / 100n / BigInt(PRECISION);

	const formattedAmount = formatValue(
		slippageAdjustedAmount,
		output.token.decimals,
	);
	const priceInUsd = output?.priceInUsd;
	const valueInUsd = priceInUsd
		? Number(formattedAmount) * priceInUsd
		: undefined;

	return {
		amount: slippageAdjustedAmount.toString(),
		valueInUsd,
		formattedAmount,
	};
}

// for manual, using the minAmoutOut from the response
export const getManualMinOutput = (output: Output) => {
	const formattedAmount = formatValue(output.minAmountOut, output.token.decimals);
	const priceInUsd = output?.priceInUsd ?? 0;
	const valueInUsd = priceInUsd * Number.parseFloat(formattedAmount);

	return {
		amount: output.minAmountOut,
		formattedAmount,
		valueInUsd,
	};
};
