require 'rails_helper'

RSpec.describe TaskItemsController, type: :controller do

  render_views

  before(:each) do
    request.accept = "application/json"
  end

  let(:user) {
    create(:user)
  }

  let(:task_list) { create(:task_list, user: user) }

  let(:valid_session) { {user_id: user.id} }

  describe 'POST #create' do
    it 'creates a task_item' do
      expect do
        post :create, params: {task_list_id: task_list.id, task_item: {name: 'name'}}, session: valid_session
      end.to change(TaskItem, :count).by 1
    end
  end

  describe 'PATCH #update' do
    it 'updates a task_item' do
      i = create(:task_item, task_list: task_list)
      patch :update, params: {task_list_id: task_list.id, id: i.id, task_item: {name: 'new name'}}, session: valid_session
      i.reload
      expect(i.name).to eq 'new name'
    end
  end

  describe 'DELETE #destroy' do
    it 'destroys the item' do
      i = create(:task_item, task_list: task_list)
      delete :destroy, params: {task_list_id: task_list.id, id: i.id}, session: valid_session
      expect(TaskItem.where(id: i.id).count).to eq 0
    end

    it 'destroys an array of items' do
      i1 = create(:task_item, task_list: task_list)
      i2 = create(:task_item, task_list: task_list)
      i3 = create(:task_item, task_list: task_list)
      delete :destroy, params: {task_list_id: task_list.id, ids: [i1.id, i2.id, i3.id]}, session: valid_session
      expect(TaskItem.where(id: [i1.id, i2.id, i3.id]).count).to eq 0
    end
  end

  describe 'PATCH complete' do
    it 'sets all given items to completed' do
      i1 = create(:task_item, task_list: task_list)
      i2 = create(:task_item, task_list: task_list)
      i3 = create(:task_item, task_list: task_list)

      patch :complete, params: {task_list_id: task_list.id, ids: [i1.id, i2.id, i3.id]}, session: valid_session

      [i1, i2, i3].each do |i|
        i.reload
        expect(i.completed).to be_truthy
      end
    end

    it 'sets all given items to not completed' do
      i1 = create(:task_item, task_list: task_list)
      i2 = create(:task_item, task_list: task_list)
      i3 = create(:task_item, task_list: task_list)

      patch :complete, params: {task_list_id: task_list.id, ids: [i1.id, i2.id, i3.id], invert: true}, session: valid_session

      [i1, i2, i3].each do |i|
        i.reload
        expect(i.completed).to be_falsey
      end
    end
  end

end