import { CONFIG } from "./config"
import {
  TokenAllowanceResult,
  TokenAllowanceRequest,
  TokenAllowanceApiParams,
} from "./types"
import { WidoError } from "./WidoError"

/**
 * Get the number of tokens that the Wido contract can spend on the user's behalf, as per the ERC-20 standard.
 */
export async function getTokenAllowance(
  request: TokenAllowanceRequest
): Promise<TokenAllowanceResult> {
  const {
    accountAddress,
    tokenAddress,
    chainId,
    fromToken,
    toToken,
    fromChainId,
    toChainId,
    tokenId,
  } = request

  const endpoint = `allowance`

  if (!chainId && !fromChainId) {
    throw new Error(`fromChainId must be set`)
  }

  const paramsObj: TokenAllowanceApiParams = {
    chain_id: fromChainId ? String(fromChainId) : String(chainId),
    account_address: accountAddress,
    from_token: fromToken,
    to_token: toToken,
  }
  if (tokenAddress) {
    paramsObj.token_address = tokenAddress
  }
  if (tokenId) {
    paramsObj.token_id = tokenId
  }
  if (toChainId) {
    paramsObj.to_chain_id = String(toChainId)
  }
  const params = new URLSearchParams(paramsObj)

  const url = `${CONFIG.WIDO_API_URL}/${endpoint}?${params}`
  const res = await fetch(url)

  if (!res.ok) {
    throw WidoError.from_api_response(await res.json())
  }

  const data: TokenAllowanceResult = await res.json()

  return {
    spender: data.spender,
    allowance: data.allowance,
  }
}
