# frozen_string_literal: true

require "em-http/middleware/json_response"

class SimpleSwap
	def initialize(api_key: CONFIG[:simpleswap_api_key])
		@api_key = api_key
	end

	def fetch_range(currency)
		req(
			:aget, "get_ranges",
			query: {
				fixed: "false",
				currency_from: currency,
				currency_to: "bch"
			}
		).then { |req|
			{ min: req.response["min"]&.to_d || 0, max: req.response["max"]&.to_d }
		}
	end

	def fetch_rate(currency)
		req(
			:aget, "get_estimated",
			query: {
				fixed: "false",
				currency_from: currency,
				currency_to: "bch",
				amount: 1
			}
		).then { |req| req.response.to_d }
	end

	def fetch_addr(currency, target)
		req(
			:apost, "create_exchange",
			body: {
				fixed: false,
				currency_from: currency,
				currency_to: "bch",
				amount: currency.downcase == "xmr" ? 0.1 : 0.01,
				address_to: target
			}.to_json
		).then(&method(:parse))
	end

	def parse(req)
		return req.response["address_from"] if req.response["address_from"]

		if req.response["error"].to_s =~ /does not fall within the range/
			raise "Network fees are too high, try again later."
		end

		raise req.response["message"] || req.response["error"] || "Error"
	end

	def req(m, path, query: {}, body: nil)
		EM::HttpRequest.new(
			"https://api.simpleswap.io/#{path}", tls: { verify_peer: true }
		).tap { |req| req.use(EM::Middleware::JSONResponse) }.public_send(
			m,
			head: {
				"Accept" => "application/json", "Content-Type" => "application/json"
			},
			query: query.merge(api_key: @api_key),
			body: body
		)
	end
end
