# frozen_string_literal: true

require_relative "credit_card_gateway"

class CreditCardCustomerGateway
	def initialize(jid, customer_id, antifraud, currency: nil)
		@jid = jid
		@customer_id = customer_id
		@gateway = CreditCardGateway.new(
			currency || customer_plan&.dig(:currency),
			antifraud
		)
	end

	def merchant_account
		@gateway.merchant_account
	end

	def check_customer_id(cid)
		return cid unless ENV["RACK_ENV"] == "production"

		raise "customer_id does not match" unless @customer_id == cid

		cid
	end

	def customer_id
		customer_id = Customer.new(nil, @jid).customer_id
		return customer_id if check_customer_id(customer_id)

		result = @gateway.customer.create
		raise "Braintree customer create failed" unless result.success?

		@customer_id = result.customer.id
		Customer.new(@customer_id, @jid).save!
		@customer_id
	end

	def customer_plan
		name = DB.exec_params(<<~SQL, [@customer_id]).first&.[]("plan_name")
			SELECT plan_name FROM customer_plans WHERE customer_id=$1 LIMIT 1
		SQL
		PLANS.find { |plan| plan[:name].to_s == name }
	end

	def client_token
		@gateway.client_token(customer_id: customer_id)
	end

	def payment_methods?
		!@gateway.customer.find(customer_id).payment_methods.empty?
	end

	def antifraud
		return if REDIS.exists?("jmp_antifraud_bypass-#{customer_id}")

		@gateway.antifraud
	end

	def with_antifraud(&blk)
		@gateway.with_antifraud(&blk)
	end

	def sale(nonce, amount)
		customer = Customer.new(@customer_id, @jid)
		raise "Please contact JMP support." if customer.trust_level == "Tombed"

		@gateway.sale(nonce, amount, customer_id: customer_id)
	end

	def default_method(nonce)
		with_antifraud do
			@gateway.payment_method.create(
				customer_id: customer_id, payment_method_nonce: nonce,
				options: {
					verify_card: true, make_default: true,
					verification_merchant_account_id: merchant_account.to_s
				}
			)
		end
	end

	def remove_method(token)
		@gateway.payment_method.delete(token)
	end
end
