class Paya::VaultService < Paya::ApplicationService
  def initialize(school, method, data={})
    @method = method
    @data = data
    super(school)
  end

  def call
    response = case @method
    when :index
      params = { params: options }
      RestClient.get(endpoint, headers.merge(params))
    when :show
      url = "#{endpoint}/#{options[:vault_id]}"
      RestClient.get(url, headers)
    when :update
      url = "#{endpoint}/#{options[:vault_id]}"
      RestClient.put(url, { accountvault: options }, headers)
    when :destroy
      url = "#{endpoint}/#{options[:vault_id]}"
      RestClient.delete(url, headers)
      return { deleted: true }
    end

    response = JSON.parse(response)
    if @method == :index
      response['accountvaults'].delete_if { |h| h['accountvault_c2'] != options[:accountvault_c2] }
    end

    response
  rescue RestClient::Exception => e
    JSON.parse(e.response.body)
  end

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

    def options
      {}.tap do |props|
        props[:vault_id] = @data[:id] if @data[:id]
        props[:accountvault_c2] = "family_#{@data[:family_id]}" if @data[:family_id].present?
        props[:payment_method] = @data[:payment_method] if @data[:payment_method].present?
        props[:account_holder_name] = @data[:account_holder_name] if @data[:account_holder_name]
        props[:billing_address] = @data[:billing_street] if @data[:billing_street]
        props[:billing_city] = @data[:billing_city] if @data[:billing_city]
        props[:billing_state] = @data[:billing_state] if @data[:billing_state]
        props[:billing_zip] = @data[:billing_zip] if @data[:billing_zip]
        props[:billing_phone] = @data[:billing_phone] if @data[:billing_phone]
        props[:exp_date] = @data[:exp_date] if @data[:exp_date]
      end
    end
end
