require 'spec_helper'

describe ApiPaymentHistoriesController, type: :controller do
  render_views

  let(:user) {FactoryGirl.create(:user)}
  let(:jam_track) {FactoryGirl.create(:jam_track)}

  before(:each) do
    controller.current_user = user
  end

  describe "index" do

    it "empty" do
      get :index, { :format => 'json'}

      response.should be_success
      body = JSON.parse(response.body)
      body['next_page'].should be_nil
      body['entries'].should eq([])
      body['total_entries'].should eq(0)
    end

    it "one item" do
      sale = Sale.create_jam_track_sale(user)
      sale.recurly_invoice_id = SecureRandom.uuid
      sale.save!

      shopping_cart = ShoppingCart.create(user, jam_track)
      sale_line_item = SaleLineItem.create_from_shopping_cart(sale, shopping_cart, nil, 'some_adjustment_uuid', nil)

      get :index, { :format => 'json'}
      response.should be_success
      body = JSON.parse(response.body)
      body['next_page'].should be_nil
      entries = body['entries']
      entries.should have(1).items
      sale_entry = entries[0]
      sale_entry['recurly_total_in_cents'].should eq(sale.recurly_total_in_cents)
      sale_json = sale_entry['sale']
      sale_json.should_not be_nil
      sale_json["line_items"].should have(1).items


      transaction = FactoryGirl.create(:recurly_transaction_web_hook, invoice_id: sale.recurly_invoice_id, transaction_type: RecurlyTransactionWebHook::VOID, user: user, transaction_at: 1.minute.from_now)

      get :index, { :format => 'json'}
      response.should be_success
      body = JSON.parse(response.body)
      body['next_page'].should be_nil
      entries = body['entries']
      entries.should have(2).items
      void_entry = entries[0]
      void = void_entry['transaction']
      void.should_not be_nil
      void['amount_in_cents'].should eq(199)
      sale_entry = entries[1]
      sale_json = sale_entry['sale']
      sale_json.should_not be_nil
      sale_json["line_items"].should have(1).items
    end
  end

end
