# frozen_string_literal: true

require_relative "./paypal_done"

class MigrateBilling
	def initialize(customer, finish: PaypalDone)
		@customer = customer
		@finish = finish
	end

	def parse(iq)
		plan_name = iq.form.field("plan_name").value.to_s
		(@customer = @customer.with_plan(plan_name)).save_plan!.then {
			Registration::Payment.for(
				iq, @customer,
				OpenStruct.new(price: 0, to_s: @customer.registered?.phone),
				finish: @finish
			)
		}.then(&:write)
	end

	def msg
		"#{@customer.customer_id} migrated to #{@customer.currency}"
	end

	def write
		Command.reply(&method(:form)).then(&method(:parse)).catch_only(
			Command::Execution::FinalStanza
		) do |s|
			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
			BLATHER.say(CONFIG[:notify_admin], msg, :groupchat)
			EMPromise.reject(s)
		end
	end

protected

	def form(stanza)
		stanza.allowed_actions = [:next]
		stanza.command << FormTemplate.render("migrate_billing")
	end
end
