# frozen_string_literal: true

require_relative "bill_plan_command"
require_relative "customer_info_form"
require_relative "financial_info"
require_relative "form_template"

class AdminCommand
	def initialize(target_customer, customer_repo)
		@target_customer = target_customer
		@customer_repo = customer_repo
	end

	def start
		@target_customer.admin_info.then { |info|
			reply(info.form)
		}.then { menu_or_done }
	end

	def reply(form)
		Command.reply { |reply|
			reply.allowed_actions = [:next, :complete]
			reply.command << form
		}
	end

	def menu_or_done(command_action=:execute)
		return Command.finish("Done") if command_action == :complete

		reply(FormTemplate.render("admin_menu")).then do |response|
			if response.form.field("action")
				handle(response.form.field("action").value, response.action)
			end
		end
	end

	def handle(action, command_action)
		if respond_to?("action_#{action}")
			send("action_#{action}")
		else
			new_context(action)
		end.then { menu_or_done(command_action) }
	end

	def new_context(q)
		CustomerInfoForm.new(@customer_repo)
			.parse_something(q).then do |new_customer|
				if new_customer.respond_to?(:customer_id)
					AdminCommand.new(new_customer, @customer_repo).start
				else
					reply(new_customer.form)
				end
			end
	end

	def action_info
		# Refresh the data
		new_context(@target_customer.customer_id)
	end

	def action_financial
		AdminFinancialInfo.for(@target_customer).then do |financial_info|
			reply(FormTemplate.render(
				"admin_financial_info",
				info: financial_info
			)).then {
				pay_methods(financial_info)
			}.then {
				transactions(financial_info)
			}
		end
	end

	def action_bill_plan
		BillPlanCommand.for(@target_customer).call
	end

	def action_cancel_account
		m = Blather::Stanza::Message.new
		m.from = CONFIG[:notify_from]
		m.body = "Your JMP account has been cancelled."
		@target_customer.stanza_to(m).then {
			EMPromise.all([
				@target_customer.stanza_to(IBR.new(:set).tap(&:remove!)),
				@target_customer.deregister!,
				@customer_repo.disconnect_tel(@target_customer)
			])
		}
	end

	def pay_methods(financial_info)
		reply(FormTemplate.render(
			"admin_payment_methods",
			**financial_info.to_h
		))
	end

	def transactions(financial_info)
		reply(FormTemplate.render(
			"admin_transaction_list",
			transactions: financial_info.transactions
		))
	end
end
