import type { Token } from "@/types/index";

/**
 * Removes duplicate tokens based on address (case-insensitive) and chainId
 * @param tokens Array of tokens to deduplicate
 * @returns Token[] with duplicates removed
 */
export function removeDuplicateTokens(tokens: Token[]): Token[] {
	const seen = new Set<string>();
	return tokens.filter((token) => {
		const key = `${token.address.toLowerCase()}-${token.chainId}`;
		if (seen.has(key)) {
			return false;
		}
		seen.add(key);
		return true;
	});
}

/**
 * Function to convert tokens from {id: Token[]} to Token[] format
 * @returns Token[] with duplicates removed
 */
export function getFormattedTokenList(tokens: { [chainId: string]: Token[] }) {
	const _tokens = Object.values(tokens ?? []);
	if (_tokens) {
		const flattenedTokens = _tokens.reduce((newArr, currentArr) => {
			return newArr.concat(...currentArr);
		}, []);
		return removeDuplicateTokens(flattenedTokens);
	}
	return [];
}
