# frozen_string_literal: true

class CustomerFinancials
	def initialize(customer_id)
		@customer_id = customer_id
	end

	def payment_methods
		BRAINTREE
			.customer
			.find(@customer_id)
			.catch { OpenStruct.new(payment_methods: []) }
			.then(PaymentMethods.method(:for_braintree_customer))
	end

	def btc_addresses
		REDIS.smembers("jmp_customer_btc_addresses-#{@customer_id}")
	end

	def add_btc_address
		REDIS.spopsadd([
			"jmp_available_btc_addresses",
			"jmp_customer_btc_addresses-#{@customer_id}"
		]).then do |addr|
			ELECTRUM.notify(
				addr,
				CONFIG[:electrum_notify_url].call(addr, @customer_id)
			)
			addr
		end
	end

	def declines
		REDIS.get("jmp_pay_decline-#{@customer_id}")
	end

	def mark_decline
		REDIS.incr("jmp_pay_decline-#{@customer_id}").then do
			REDIS.expire("jmp_pay_decline-#{@customer_id}", 60 * 60 * 24)
		end
	end

	class TransactionInfo
		value_semantics do
			transaction_id String
			created_at Time
			amount BigDecimal
			note String, coerce: ->(x) { x || "" }
		end

		def formatted_amount
			"$%.4f" % amount
		end
	end

	TRANSACTIONS_SQL = <<~SQL
		SELECT
			transaction_id,
			created_at,
			amount,
			note
		FROM transactions WHERE customer_id = $1;
	SQL

	def transactions
		txns = DB.query_defer(TRANSACTIONS_SQL, [@customer_id])

		txns.then do |rows|
			rows.map { |row|
				TransactionInfo.new(**row.transform_keys(&:to_sym))
			}
		end
	end
end
