import { Chain, Token } from "@src/models";
import { isServer } from "@src/utils";

/**
 * Retrieves custom tokens from localStorage and adds them to the provided chains
 * @param chains - The original chains to which custom tokens should be added
 * @returns A new array of chains with custom tokens added
 */
export const addCustomTokensToChains = (chains: Chain[]): Chain[] => {
  const customTokensObj = !isServer
    ? JSON.parse(localStorage.getItem("custom-tokens") || "{}")
    : {};

  const customTokens = Object.entries(customTokensObj).reduce(
    (acc, [chainId, tokensObj]) => {
      acc[chainId] = Object.values(tokensObj as Record<string, Token>);
      return acc;
    },
    {} as Record<string, Token[]>,
  );

  return chains.map((chain) => {
    const chainCustomTokens = customTokens[chain.chainId] || [];

    if (chainCustomTokens.length === 0) {
      return chain;
    }

    const filteredCustomTokens = chainCustomTokens.filter(
      (customToken: Token) =>
        !chain.tokens.some(
          (existingToken) =>
            existingToken.address.toLowerCase() ===
            customToken.address.toLowerCase(),
        ),
    );

    if (filteredCustomTokens.length === 0) {
      return chain;
    }

    return {
      ...chain,
      tokens: [
        ...chain.tokens,
        ...filteredCustomTokens.map((customToken: Token) => ({
          ...customToken,
        })),
      ],
    };
  });
};
