require 'rails_helper'

RSpec.describe UserRewards::HypeTrainsController 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 { get :index }
      it_behaves_like "it returns a success response"
    end
  end

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

      before { post :grant_rewards }

      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
        {
          hype_train: {
              channel_id: "123",
              user_id: "456",
              participated_at: "2020-01-02T03:04",
              time_zone: "UTC",
          }
        }
      end

      describe "when no hype train and rewards are found" do
        before do
          expect(UserRewards::HypeTrain).to receive(:grant_rewards).and_return([nil, []])
          post :grant_rewards, params: params
        end

        it_behaves_like "it returns a success response"
      end

      describe "when hype train and rewards are found" do
        let(:hype_train) do
          {
            config: {
                difficulty: :EASY
            },
            level_progress: {
              progression: 80,
              goal: 100
            },
            started_at: Time.now,
            ended_at: Time.now
          }
        end
        let(:rewards) do
          [
            {
              id: "999",
              type: :EMOTE
            }
          ]
        end
        let(:participation_total) do
          [
            {
              source: :BITS,
              action: :CHEER,
              quantity: 100
            }
          ]
        end

        before do
          expect(UserRewards::HypeTrain).to receive(:grant_rewards).and_return([hype_train, rewards, rewards, participation_total])
          post :grant_rewards, params: params
        end

        it_behaves_like "it returns a success response"
        it "renders successfully" do
          expect(flash[:error]).not_to be_present
          expect(flash[:warning]).not_to be_present
        end
      end
      describe "when service raises and error" do
        before do
          expect(UserRewards::HypeTrain).to receive(:grant_rewards).and_raise('something went wrong')
          post :grant_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