require 'rails_helper'

RSpec.describe UserRewards::BitsBadgeTiersController do
  include_context "mocked permissions"

  let(:permission) { "rewards" }

  describe "index" do
    context "a user without permission" do
      include_context "an unauthorized user"

      before do
        get :index
      end

      it_behaves_like "it redirects the user and displays an error"
    end

    context "a user with permission" do
      include_context "an authorized user"

      before do
        get :index
      end

      it_behaves_like "it returns a success response"
    end
  end

  describe "grant_unlocked_rewards" do
    context "a user without permission" do
      include_context "an unauthorized user"

      before do
        post :grant_unlocked_rewards
      end

      it_behaves_like "it redirects the user and displays an error"
    end

    context "a user with permission" do
      include_context "an authorized user"
      include_context 'it creates any tracking call'

      let(:params) do
        {
          bits_badge_tier: {
            channel_id: "123",
            user_id: "456"
          }
        }
      end

      describe "succeeds granting rewards and returns badge tiers" do
        before do
          expect(UserRewards::BitsBadgeTier).to receive(:grant_unlocked_rewards).and_return(12345)
          expect(UserRewards::BitsBadgeTier).to receive(:unlocked_emotes).and_return([])
          post :grant_unlocked_rewards, params: params
        end

        it_behaves_like "it returns a success response"
      end

      describe "fails to grant rewards" do
        before do
          expect(UserRewards::BitsBadgeTier).to receive(:grant_unlocked_rewards).and_raise("some error")
          post :grant_unlocked_rewards, params: params
        end

        it_behaves_like "it returns a success response"
        it "renders successfully" do
          expect(flash[:error]).to be_present
        end
      end
    end
  end

end