class Payjunction::TransactionService < ApplicationService
  def initialize(school, family, options)
    @school = school
    @family = family
    @options = options
  end

  def call
    response = JSON.parse(RestClient.post(url, body, headers))
    status = { success: response['response']['approved'] }
    return status if status[:success]

    status.tap { |s| s[:error] = response['response'] }
  rescue RestClient::Exception => e
    { success: false, error: e.response.body }
  end

  private
    def config
      @config ||= @school.find_or_build_payjunction_config
    end

    def payjunction_secrets
      Rails.application.secrets.payjunction[config.environment.to_sym]
    end

    def url
      "#{payjunction_secrets[:url]}/transactions"
    end

    def key
      Base64.urlsafe_encode64("#{config.username}:#{config.decrypted_password}")
    end

    def headers
      {
        Authorization: "Basic #{key}",
        'X-PJ-Application-Key': payjunction_secrets[:key],
        'Content-Length': 0
      }
    end

    def amount_to_currency
      '%.2f' % @options[:amount]
    end

    def body
      {}.tap do |props|
        props[:action] = :CHARGE
        props[:tokenId] = @options[:token]
        props[:billingFirstName] = @options[:first_name]
        props[:billingLastName] = @options[:last_name]
        props[:billingAddress] = @options[:address]
        props[:billingCity] = @options[:city]
        props[:billingState] = @options[:state]
        props[:billingZip] = @options[:zip]
        props[:billingEmail] = @options[:email]
        props[:billingPhone] = @options[:phone]
        props[:note] = @options[:memo]
        props[:amountBase] = amount_to_currency
        props[:billingIdentifier] = @family.id
        props[:achType] = :PPD
        return props unless @options[:invoice_id]

        props[:invoiceNumber] = @options[:invoice_id]
      end
    end
end
