/**
 * CCIP fee estimation for Chain138 <-> Ethereum.
 * Uses default or optional router/relay lookup.
 */

const CHAIN_138 = 138;
const CHAIN_ETHEREUM = 1;

/** Default LINK fee in wei (18 decimals) - ~0.1 LINK */
const DEFAULT_CCIP_FEE = '100000000000000000';

export interface CCIPFeeEstimate {
  feeLink: string;
  source: 'default' | 'estimated';
}

/**
 * Estimate CCIP fee for token transfer 138 -> 1 or 1 -> 138.
 * Extend with CCIP Router getFee() or relay API when available.
 */
export async function getCCIPFeeEstimate(
  sourceChain: number,
  destChain: number,
  token: string,
  amount: string
): Promise<CCIPFeeEstimate> {
  if (
    !((sourceChain === CHAIN_138 && destChain === CHAIN_ETHEREUM) || (sourceChain === CHAIN_ETHEREUM && destChain === CHAIN_138))
  ) {
    return { feeLink: '0', source: 'default' };
  }
  const routerUrl = process.env.CCIP_ROUTER_QUOTE_URL;
  if (routerUrl) {
    try {
      const res = await fetch(routerUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sourceChain, destChain, token, amount }),
        signal: AbortSignal.timeout(3000),
      });
      if (res.ok) {
        const data = (await res.json()) as { fee?: string };
        if (data.fee) return { feeLink: data.fee, source: 'estimated' };
      }
    } catch {
      /* fallback */
    }
  }
  return { feeLink: DEFAULT_CCIP_FEE, source: 'default' };
}
