import type {
	ComparisonRoute,
	EndPoint,
	Quote,
} from "../hooks/apis/useFetchQuote";

export interface FormattedQuoteData extends Quote {
	destRate: number;
	srcRate: number;
	primaryInput: EndPoint;
	primaryOutput: EndPoint;
	receiverAddressAdded: boolean;
	sortedComparisonRoutes: ComparisonRoute[];
	slippage: string;
}

export const getQuoteData = (quote: Quote, slippage?: string) => {
	if (!quote) return null;

	const destRate = quote.output[0].priceInUsd / quote.input[0].priceInUsd;
	const srcRate = quote.input[0].priceInUsd / quote.output[0].priceInUsd;

	// @note: not taking receiver address from quote response
	// to save an unnecessary quote call
	const receiverAddressAdded =
		quote.sender.toLowerCase() !== quote.receiver.toLowerCase();

	const sortedComparisonRoutes = quote?.comparisionRoutes?.sort(
		(a, b) => a.feesInUsd - b.feesInUsd,
	);

	const outputFormatted: EndPoint[] = [];
	if (slippage) {
		for (const item of quote.output) {
			const amount = BigInt(item.amount);
			const PRECISION = 10000;
			const _slippage = Number(slippage) * PRECISION;

			const amountToDeduct =
				(amount * BigInt(_slippage)) / (100n * BigInt(PRECISION));

			const minAmount = amount - amountToDeduct;

			outputFormatted.push({
				...item,
				slippageAdjustedAmount: minAmount.toString(),
			});
		}
	}

	return {
		...quote,
		destRate,
		srcRate,
		primaryInput: quote.input[0],
		primaryOutput: quote.output[0],
		receiverAddressAdded,
		sortedComparisonRoutes,
		output: slippage ? outputFormatted : quote.output,
		slippage,
	} as FormattedQuoteData;
};
