# frozen_string_literal: true

require "bigdecimal"
require "em-http"
require "em_promise"
require "em-synchrony/em-http" # For apost vs post
require "json"
require "securerandom"

class Churnbuster
	def initialize(
		account_id: CONFIG.dig(:churnbuster, :account_id),
		api_key: CONFIG.dig(:churnbuster, :api_key)
	)
		@account_id = account_id
		@api_key = api_key
	end

	def failed_payment(customer, amount, txid)
		post_json(
			"https://api.churnbuster.io/v1/failed_payments",
			{
				customer: format_customer(customer),
				payment: format_tx(customer, amount, txid)
			}
		)
	end

	def successful_payment(customer, amount, txid)
		post_json(
			"https://api.churnbuster.io/v1/successful_payments",
			{
				customer: format_customer(customer),
				payment: format_tx(customer, amount, txid)
			}
		)
	end

	def cancellation(customer)
		post_json(
			"https://api.churnbuster.io/v1/cancellations",
			{
				customer: format_customer(customer),
				subscription: {
					source: "braintree",
					source_id: customer.customer_id
				}
			}
		)
	end

protected

	def format_tx(customer, amount, txid)
		{
			source: "braintree",
			source_id: txid,
			amount_in_cents: (amount * 100).to_i,
			currency: customer.currency
		}
	end

	def format_customer(customer)
		unprox = ProxiedJID.new(customer.jid).unproxied.to_s
		email = "#{unprox.gsub(/@/, '=40').gsub(/\./, '=2e')}@smtp.cheogram.com"
		{
			source: "braintree",
			source_id: customer.customer_id,
			email: email,
			properties: {}
		}
	end

	def post_json(url, data)
		EM::HttpRequest.new(
			url,
			tls: { verify_peer: true }
		).apost(
			head: {
				"Authorization" => [@account_id, @api_key],
				"Content-Type" => "application/json"
			},
			body: data.to_json
		)
	end
end
