import type { Token } from "@/types/index";
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);
		// although sorting is already done on the server side, we need to account for imported tokens
		updatedTokenList[chainId] = [...tokenList].sort((tokenA, tokenB) => {
			/**
			 * Sorting Priority:
			 * 1. Tokens with non-zero balanceInUsd (higher first)
			 * 2. Among zero-balance tokens, verified tokens come first
			 * 3. Among unverified tokens, non-imported come before imported
			 */

			const tokenAHasBalance = tokenA?.balanceInUsd && tokenA.balanceInUsd > 0;
			const tokenBHasBalance = tokenB?.balanceInUsd && tokenB.balanceInUsd > 0;

			if (tokenAHasBalance !== tokenBHasBalance) {
				return tokenBHasBalance ? 1 : -1; // tokens with balance first
			}
			if (tokenAHasBalance && tokenBHasBalance) {
				return (tokenB.balanceInUsd ?? 0) - (tokenA.balanceInUsd ?? 0);
			}

			if (tokenA.isVerified !== tokenB.isVerified) {
				return tokenB.isVerified ? 1 : -1; // verified tokens before unverified
			}

			if (tokenA.isImported !== tokenB.isImported) {
				return tokenA.isImported ? 1 : -1; // non-imported before imported
			}

			return 0;
		});
	}

	return updatedTokenList;
}
