/**
 * Resolve chain input — accepts both chain names and chain IDs.
 * 
 * AI agents reading agent.json get chain_id (8453, 43114, etc.)
 * but our API routes use chain names (base, avalanche, etc.).
 * This helper accepts either and returns the canonical name.
 *
 * Usage:
 *   const chain = resolveChain(searchParams.get('chain'));
 *   if (!chain) return NextResponse.json({ error: 'Invalid chain...' }, { status: 400 });
 */

const CHAIN_ID_TO_NAME: Record<string, string> = {
  '8453':  'base',
  '43114': 'avalanche',
  '42161': 'arbitrum',
  '137':   'polygon',
};

const VALID_NAMES = new Set(['base', 'avalanche', 'arbitrum', 'polygon']);

/**
 * Resolves a chain identifier to its canonical name.
 * @param input - Chain name ("base") or chain ID ("8453") or null
 * @param defaultChain - Fallback if input is null/empty (default: "base")
 * @returns Canonical chain name or null if invalid
 */
export function resolveChain(input: string | null | undefined, defaultChain = 'base'): string | null {
  if (!input) return defaultChain;
  
  const normalized = input.trim().toLowerCase();
  
  // Direct name match
  if (VALID_NAMES.has(normalized)) return normalized;
  
  // Chain ID match
  if (CHAIN_ID_TO_NAME[normalized]) return CHAIN_ID_TO_NAME[normalized];
  
  return null;
}

/** All valid chain names */
export const SUPPORTED_CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'];
