/**
 * Chain138 swap quote service.
 * Tries 1inch API (chain 138 if supported); falls back to same-asset or amount passthrough.
 */

const ONEINCH_API = 'https://api.1inch.dev/swap/v5.2';
const CHAIN_138 = 138;

export interface Chain138SwapQuote {
  amountOut: string;
  amountOutMin: string;
  provider: string;
  source: 'api' | 'passthrough';
}

export async function getChain138SwapQuote(
  tokenIn: string,
  tokenOut: string,
  amountIn: string
): Promise<Chain138SwapQuote> {
  const amount = amountIn;
  try {
    const apiKey = process.env.ONEINCH_API_KEY;
    const headers: Record<string, string> = { Accept: 'application/json' };
    if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
    const url = `${ONEINCH_API}/${CHAIN_138}/quote?src=${tokenIn}&dst=${tokenOut}&amount=${amount}`;
    const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
    if (!res.ok) throw new Error(`1inch ${res.status}`);
    const data = (await res.json()) as { toAmount?: string; dstAmount?: string };
    const toAmount = data.toAmount ?? data.dstAmount ?? amount;
    const amountOutMin = Math.floor(parseFloat(toAmount) * 0.995).toString();
    return { amountOut: toAmount, amountOutMin, provider: '1inch', source: 'api' };
  } catch {
    if (tokenIn.toLowerCase() === tokenOut.toLowerCase()) {
      return { amountOut: amount, amountOutMin: amount, provider: 'passthrough', source: 'passthrough' };
    }
    return { amountOut: amount, amountOutMin: amount, provider: 'EnhancedSwapRouter', source: 'passthrough' };
  }
}
