import { API_URLS } from "@/api";
import { TxVersion } from "@/common";
import axios from "axios";
import Decimal from "decimal.js";

// Types
export type SwapType = "BaseIn" | "BaseOut";

export interface SwapParams {
  inputMint: string;
  outputMint: string;
  amount: string;
  slippage: number;
  swapType: SwapType;
  txVersion: TxVersion;
}

export interface SwapResponse {
  data?: any;
  error?: string;
  openTime?: number;
}

/**
 * Computes swap details based on provided parameters
 * @param params SwapParams object containing swap configuration
 * @returns Promise<SwapResponse>
 */
export async function computeSwap(params: SwapParams): Promise<SwapResponse> {
  const { inputMint, outputMint, amount, slippage, swapType, txVersion } = params;

  try {
    // Validate inputs
    if (!inputMint || !outputMint) {
      throw new Error("Input and output mints are required");
    }

    const amountDecimal = new Decimal(amount.trim() || 0);
    if (amountDecimal.isZero()) {
      throw new Error("Amount must be greater than 0");
    }

    // Convert slippage to basis points
    const slippageBps = new Decimal(slippage * 10000).toFixed(0);

    // Construct API URL
    const apiTrail = swapType === "BaseOut" ? "swap-base-out" : "swap-base-in";
    const url = `${API_URLS.SWAP_HOST}${API_URLS.SWAP_COMPUTE}${apiTrail}`;

    // Prepare query parameters
    const queryParams = new URLSearchParams({
      inputMint,
      outputMint,
      amount: amount.toString(),
      slippageBps,
      txVersion: txVersion === TxVersion.V0 ? "V0" : "LEGACY",
    });

    // Make API request
    const response = await axios.get(`${url}?${queryParams}`);

    console.log("computeSwapresponse", response);

    return {
      data: response.data?.data,
      openTime: response.data?.openTime,
      error: response.data?.msg,
    };
  } catch (error) {
    console.log("computeSwaperror", error);
    return {
      error: error instanceof Error ? error.message : "Unknown error occurred",
    };
  }
}
