module Prime
  class CoingeckoClient
    BASE_URL = 'https://api.coingecko.com/api/'.freeze
    DEFAULT_TIMEOUT = 3

    class Error         < StandardError; end
    class NotFoundError < Error; end

    def token_price(token)
      params = { ids: token, vs_currencies: 'usd' }
      get('v3/simple/price', params: params)[token]['usd']
    end

    private

    def get(path, headers: {}, params: {}, timeout: DEFAULT_TIMEOUT)
      headers['params'] = params

      resp = RestClient::Request.execute(
        method: :get,
        url: "#{BASE_URL}#{path}",
        headers: headers,
        timeout: timeout
      )
      JSON.parse(resp.body)
    rescue RestClient::NotFound => err
      Rails.logger.error("Coingecko Path: #{path} Params: #{params} Error: #{err}")
      raise Prime::CoingeckoClient::NotFoundError, err
    rescue StandardError => err
      Rails.logger.error("Coingecko Path: #{path} Params: #{params} Error: #{err}")
      raise Prime::CoingeckoClient::Error, err
    end
  end
end
