/**
 * Allowlist for DEX routers, bridge contracts, and tokens.
 * Validate all hop protocols/addresses against this config.
 */

export const ALLOWED_DEX_ROUTERS: Record<string, string[]> = {
  '138': ['EnhancedSwapRouter', '1inch', 'UniswapV3', 'Dodoex', 'Balancer', 'Curve', 'Direct'],
  '651940': ['AlltraDEX', 'EnhancedSwapRouter', '1inch', 'UniswapV3', 'Direct'],
  '1729': ['Plenty', 'Quipuswap', 'SpicySwap'],
};

export const ALLOWED_BRIDGE_PROVIDERS = ['CCIP', 'Wrap Protocol', 'Allbridge Core', 'Bridge Vault', 'AlltraAdapter', 'Hop Protocol'];

export const ALLOWED_CHAIN138_TOKENS: string[] = [
  '0xf22258f57794CC8E06237084b353Ab30fFfa640b', // cUSDC
  '0x93E66202A11B1772E55407B32B44e5Cd8eda7f22', // cUSDT
  '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
  '0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03', // LINK (CCIP fee routing)
];

export const ALLOWED_ALL_MAINNET_TOKENS: string[] = [
  '0xa95EeD79f84E6A0151eaEb9d441F9Ffd50e8e881', // AUSDC (USDC on ALL Mainnet)
  '0x015B1897Ed5279930bC2Be46F661894d219292A6', // AUSDT (primary)
  '0x798F6762BB40d6801A593459d08F890603D3979C', // WETH
];

export const ALLOWED_TEZOS_TOKENS: string[] = [
  'KT1T87QbpXEVgkwsNPzz8iRoah3SS3D1MDmh', // USDtz
  'KT1LN4LPSqTMS7Sd2CJw4bbDGR5Mv2t68Fy9', // USDtz legacy
];

export function isAllowedDex(chainId: number, protocol: string): boolean {
  const list = ALLOWED_DEX_ROUTERS[String(chainId)] ?? [];
  return list.some((p) => p.toLowerCase() === protocol.toLowerCase());
}

export function isAllowedBridge(provider: string): boolean {
  return ALLOWED_BRIDGE_PROVIDERS.includes(provider);
}

export function isAllowedToken(chainId: number, address: string): boolean {
  const list =
    chainId === 138
      ? ALLOWED_CHAIN138_TOKENS
      : chainId === 651940
        ? ALLOWED_ALL_MAINNET_TOKENS
        : chainId === 1729
          ? ALLOWED_TEZOS_TOKENS
          : [];
  return list.some((a) => a.toLowerCase() === address.toLowerCase());
}

export function validateRouteAllowlist(hops: Array<{ protocol: string; chain: string; asset_in: string }>): string[] {
  const errors: string[] = [];
  const chainIds: Record<string, number> = { CHAIN138: 138, ALL_MAINNET: 651940, HUB_EVM: 1, TEZOS: 1729 };
  for (const h of hops) {
    const cid = chainIds[h.chain] ?? 138;
    if (h.protocol && !isAllowedBridge(h.protocol) && !isAllowedDex(cid, h.protocol)) {
      errors.push(`Protocol ${h.protocol} not in allowlist`);
    }
  }
  return errors;
}
