import type { Token } from "@providers/ConfigProvider";
type TokenId = { [chainId: number]: Token[] };

/**
 * This function adds imported token to the token list
 * and sorts the tokens based on usd values
 */

export function addImportedTokens(
	restTokens: TokenId,
	importedTokens?: TokenId,
) {
	const restTokensAvail = restTokens && Object.keys(restTokens)?.length > 0;
	if (!restTokensAvail) return {};

	const updatedTokenList = { ...restTokens };
	if (importedTokens) {
		for (const _chainId of Object.keys(importedTokens)) {
			const chainId = Number(_chainId);
			const importedChainTokens = importedTokens[chainId];

			const existingTokens = updatedTokenList[chainId] || [];
			updatedTokenList[chainId] = [...importedChainTokens, ...existingTokens];
		}
	}

	// Sort the entire updatedTokenList after merging
	for (const [chainIdString, tokenList] of Object.entries(updatedTokenList)) {
		const chainId = Number(chainIdString);
		// @note: can get rid of sorting here?
		// sorting is already done on the server side
		updatedTokenList[chainId] = [...tokenList].sort((tokenA, tokenB) => {
			// If tokenA has balanceInUsd, sort descending (higher value first)
			if (tokenA?.balanceInUsd !== undefined) {
				return tokenB?.balanceInUsd === undefined
					? -1
					: tokenB?.balanceInUsd - tokenA?.balanceInUsd;
			}
			// If tokenA doesn't have valueInUsd, sort ascending (any value comes after)
			return 1;
		});
	}

	return updatedTokenList;
}
