/**
 * Gas Oracle Integration - Fetch gas price recommendations
 */

export interface GasPriceRecommendation {
  slow: {
    maxFeePerGas: string
    maxPriorityFeePerGas: string
  }
  standard: {
    maxFeePerGas: string
    maxPriorityFeePerGas: string
  }
  fast: {
    maxFeePerGas: string
    maxPriorityFeePerGas: string
  }
  estimatedBaseFee: string
  blockNumber: number
}

/**
 * Fetch gas prices from Etherscan API
 */
export async function fetchGasPrices(): Promise<GasPriceRecommendation | null> {
  try {
    const apiKey = import.meta.env.VITE_ETHERSCAN_API_KEY || 'YourApiKeyToken'
    const apiUrl = apiKey && apiKey !== 'YourApiKeyToken' 
      ? `https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=${apiKey}`
      : 'https://api.etherscan.io/api?module=gastracker&action=gasoracle'
    
    const response = await fetch(apiUrl)
    const data = await response.json()

    if (data.status === '1' && data.result) {
      const result = data.result
      return {
        slow: {
          maxFeePerGas: (parseInt(result.SafeGasPrice) * 1e9).toString(),
          maxPriorityFeePerGas: (parseInt(result.SafeGasPrice) * 0.5e9).toString(),
        },
        standard: {
          maxFeePerGas: (parseInt(result.ProposeGasPrice) * 1e9).toString(),
          maxPriorityFeePerGas: (parseInt(result.ProposeGasPrice) * 0.5e9).toString(),
        },
        fast: {
          maxFeePerGas: (parseInt(result.FastGasPrice) * 1e9).toString(),
          maxPriorityFeePerGas: (parseInt(result.FastGasPrice) * 0.5e9).toString(),
        },
        estimatedBaseFee: (parseInt(result.suggestBaseFee || '0') * 1e9).toString(),
        blockNumber: parseInt(result.LastBlock || '0'),
      }
    }
    return null
  } catch (error) {
    console.error('Failed to fetch gas prices:', error)
    return null
  }
}

/**
 * Get recommended gas price based on urgency
 */
export function getRecommendedGasPrice(
  recommendations: GasPriceRecommendation,
  urgency: 'slow' | 'standard' | 'fast' = 'standard'
) {
  return recommendations[urgency]
}
