export const CHAIN_ALIASES: Record<string, string> = {
  eth: "ethereum",
  ethereum: "ethereum",
  base: "base",
  bnb: "bsc",
  bsc: "bsc",
  sol: "solana",
  solana: "solana",
};

export const EVM_CHAIN_TYPES = new Set(["ethereum", "base", "bsc"]);

function normalizeChainKey(chainType: string): string {
  const normalized = String(chainType || "").trim().toLowerCase();
  return CHAIN_ALIASES[normalized] || normalized;
}

export function normalizeRequiredChainType(
  chainType: string,
  errorMessage: string = "chain_type is required"
): string {
  const normalized = normalizeChainKey(chainType);
  if (!normalized) {
    throw new Error(errorMessage);
  }

  return normalized;
}

export function parseChainStringMap(raw: string | undefined, envName: string): Record<string, string> {
  if (!raw) {
    return {};
  }

  try {
    const parsed = JSON.parse(raw) as Record<string, unknown>;
    return Object.entries(parsed).reduce<Record<string, string>>((accumulator, [chainType, value]) => {
      if (typeof value === "string" && value.trim()) {
        const normalizedChain = normalizeChainKey(chainType);
        if (normalizedChain) {
          accumulator[normalizedChain] = value.trim();
        }
      }
      return accumulator;
    }, {});
  } catch {
    throw new Error(`${envName} must be valid JSON`);
  }
}
