import axios from 'axios';
import { tokenAggUrl } from '../config';

export async function fetchQuote(params: {
  chainId: number;
  tokenIn: string;
  tokenOut: string;
  amountIn: string;
}) {
  const base = tokenAggUrl();
  const q = new URLSearchParams({
    chainId: String(params.chainId),
    tokenIn: params.tokenIn,
    tokenOut: params.tokenOut,
    amountIn: params.amountIn,
  });
  const { data } = await axios.get(`${base}/api/v1/quote?${q}`, { timeout: 60000 });
  return data;
}

export async function fetchRoutePlan(body: {
  sourceChainId: number;
  destinationChainId: number;
  tokenIn: string;
  tokenOut: string;
  amountIn: string;
  recipient?: string;
  maxSlippageBps?: number;
}) {
  const { data } = await axios.post(
    `${tokenAggUrl()}/api/v2/routes/plan`,
    {
      sourceChainId: body.sourceChainId,
      destinationChainId: body.destinationChainId,
      tokenIn: body.tokenIn,
      tokenOut: body.tokenOut,
      amountIn: body.amountIn,
      recipient: body.recipient,
      constraints: { maxSlippageBps: body.maxSlippageBps ?? 50, allowBridge: false },
    },
    { timeout: 120000 },
  );
  return data;
}

export async function fetchExecutionPlan(body: {
  sourceChainId: number;
  destinationChainId: number;
  tokenIn: string;
  tokenOut: string;
  amountIn: string;
  recipient: string;
  maxSlippageBps?: number;
}) {
  const { data } = await axios.post(
    `${tokenAggUrl()}/api/v2/routes/internal-execution-plan`,
    {
      sourceChainId: body.sourceChainId,
      destinationChainId: body.destinationChainId,
      tokenIn: body.tokenIn,
      tokenOut: body.tokenOut,
      amountIn: body.amountIn,
      recipient: body.recipient,
      constraints: { maxSlippageBps: body.maxSlippageBps ?? 50, allowBridge: false },
    },
    { timeout: 120000 },
  );
  return data;
}

export async function fetchProviderCapabilities(chainId: number) {
  const { data } = await axios.get(`${tokenAggUrl()}/api/v2/providers/capabilities?chainId=${chainId}`, {
    timeout: 30000,
  });
  return data;
}
