import { ChainID } from '../../chains.js';
import { isNativeEvmToken, WRAPPED_ETH_ADDRESSES } from '../../constants.js';

type LiquidSwapQuoteParams = {
  tokenIn: string;
  tokenOut: string;
  amountIn: string;
};

export type LiquidSwapQuoteResponse = {
  success: boolean;
  amountIn: string;
  amountOut: string;
  averagePriceImpact: string;
};

const LIQUID_SWAP_API_URL = 'https://api.liqd.ag';

export class LiquidSwapQuoteProvider {
  public async getQuote(params: LiquidSwapQuoteParams): Promise<LiquidSwapQuoteResponse> {
    if (isNativeEvmToken(params.tokenOut)) {
      params.tokenOut = WRAPPED_ETH_ADDRESSES[ChainID.Hyperliquid];
    }

    if (isNativeEvmToken(params.tokenIn)) {
      params.tokenIn = WRAPPED_ETH_ADDRESSES[ChainID.Hyperliquid];
    }

    const url = `${LIQUID_SWAP_API_URL}/v2/route?tokenIn=${params.tokenIn}&tokenOut=${params.tokenOut}&amountIn=${params.amountIn}`;
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error('Failed to fetch quote from LiquidSwap API');
    }

    const data: LiquidSwapQuoteResponse = await response.json();

    return data;
  }
}
