class Payments::Payjunction::ProcessPaymentService < ApplicationService
  include Payments::Payjunction::Httpable

  def initialize(school, options, contact, type)
    @school = school
    @contact = contact
    @vault = payment_information(options, type)
    @data = {
      terminalId: account(type).account_id,
      billingFirstName: options[:first_name],
      billingLastName: options[:last_name],
      amountBase: sprintf('%.2f', options[:amount]),
      action: options[:action]
    }
  end

  def call
    @data[:vaultId] = Payments::Payjunction::VaultService.call(
      @school,
      :create,
      @contact.external_id,
      @vault
    )['vaultId']
    path = '/transactions'
    response = request('Post', path, @school, @data)
    @contact.delete_vaults
    response
  end

  private
    def account(type)
      accounts = @school.payjunction_accounts
      type == :ach ? accounts.ach.open : accounts.credit_card.open
    end

    def payment_information(options, type)
      case type
      when :ach
        {
          achRoutingNumber: options[:routing_number],
          achAccountNumber: options[:account_number],
          achAccountType: options[:account_type],
          achType: options[:type]
        }
      when :credit_card
        month, year = options[:expiration].split('/')
        {
          cardNumber: options[:number],
          cardExpMonth: month,
          cardExpYear: year,
          address: options[:adress],
          zip: options[:zip]
        }
      end
    end
end
