class Threoze::Payjunction::VaultService < Threoze::Payjunction::ApplicationService
  def call
    response = case @action
    when :show
      return {} if pay_method[:VaultID].blank?

      RestClient.get("#{url}/#{pay_method[:VaultID]}", headers)
    when :create
      RestClient.post("#{url}/#{@params[:vault_id]}", body, headers)
    when :update
      RestClient.put("#{url}/#{@params[:vault_id]}", body, headers)
    when :destroy
      RestClient.delete("#{url}/#{@params[:vault_id]}", headers)
      { success: true }
    end
    return json_parse(response).merge(name: pay_method[:Name]) if @action == :show

    options = if @action == :destroy
      { vault_id: @params[:vault_id] }
    else
      json_parse(response).merge(name: @params[:billingname] || @params[:name])
    end
    Threoze::PayMethodService.call(@school, @action, options)
  rescue RestClient::Exception => e
    json_parse(e.response.body)
  end

  private
    def pay_method
      @pay_method ||= Threoze::PayMethodService.call(@school, :show)
    end

    def customer_id
      Threoze::PayAccountService.call(@school)['ClientID']
    end

    def endpoint
      "customers/#{customer_id}/vaults"
    end

    def body
      {}.tap do |props|
        if @params[:payment_method].downcase.to_sym == :ach
          props[:achType] = @params[:ach_type]
        end

        if @action.to_sym == :create
          props[:tokenId] = @params[:token]
          props[:address] = @params[:billingaddress1]
          props[:city] = @params[:billingcity]
          props[:state] = @params[:billingstate]
          props[:zip] = @params[:billingzip]
        else
          props[:cardExpMonth] = @params[:expiration_month]
          props[:cardExpYear] = @params[:expiration_year]
          props[:address] = @params[:address]
          props[:city] = @params[:city]
          props[:state] = @params[:state]
          props[:zip] = @params[:zip]
        end
      end
    end
end
