class Paya::TransactionService < Paya::ApplicationService
  def initialize(school, method, options={})
    @method = method
    @options = options
    @subtotal = options[:subtotal].to_f.round(2)
    @surcharge = options[:surcharge].to_f.round(2)
    super(school)
  end

  def call
    return unless @method == :create

    JSON.parse(RestClient.post(endpoint, { transaction: data }, headers))
  end

  private
    def endpoint
      "#{base_uri}/transactions"
    end

    def data
      {}.tap do |props|
        props[:account_vault_id] = @options[:vault_id]
        props[:action] = ach? ? 'debit' : 'sale'
        props[:contact_id] = @options[:contact_id]
        props[:location_id] = location_id
        props[:payment_method] = @options[:payment_method]
        props[:product_transaction_id] = @options[:product_transaction_id]
        props[:subtotal_amount] = @subtotal.to_s
        props[:surcharge_amount] = @surcharge.to_s
        props[:transaction_amount] = transaction_amount.to_s
        props[:transaction_api_id] = Time.now.to_i.to_s
        props[:ach_sec_code] = 'WEB' if ach? && @options[:family_initiated]
      end
    end

    def ach?
      @options[:payment_method] == 'ach'
    end

    def transaction_amount
      (@surcharge + @subtotal).round(2)
    end
end
