require 'rails_helper'

RSpec.describe RevenueReporting::PayoutDetailsController do
  include_context 'mocked permissions'

  let(:permission) { 'revenue_reporting' }
  let(:params) do
    {
      payout_details: {
        channel_id: channel_id
      }
    }
  end
  let(:channel_id) { '144364159' }
  let(:channel_name) { 'shroud' }

  describe '#index' do
    describe 'permissions' do
      context 'a user with appropriate permissions' do
        include_context 'an authorized user'

        before do
          get :index
        end

        it_behaves_like 'it returns a success response'
      end

      context 'a user without appropriate permissions' do
        include_context 'an unauthorized user'

        before do
          get :index
        end

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

    describe 'unable to find user by channel id' do
      include_context 'an authorized user'

      before do
        allow(Twitch::User).to receive(:find).with(channel_id).and_return(nil)
      end

      context 'user redirected' do
        before do
          get :index, params
        end

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

    describe 'unable to find user by login id' do
      include_context 'an authorized user'

      let(:params) do
        {
          payout_details: {
            channel_login: channel_login
          }
        }
      end

      let(:channel_login) { 'nuclear' }

      before do
        allow(Twitch::User).to receive(:find_by_login).with(channel_login).and_return(nil)
      end

      context 'user redirected' do
        before do
          get :index, params
        end

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

    describe 'happy path' do
      include_context 'an authorized user'

      let(:user) do
        double(:user, id: channel_id)
      end

      before do
        allow(Twitch::User).to receive(:find).with(channel_id).and_return(user)
        allow(RevenueReporting::PayoutDetail).to receive(:all_prime).with(channel_id).and_return([1, 2, 3])
      end

      context 'successfully set payout details' do
        before do
          get :index, params
        end

        it_behaves_like 'it returns a success response'
      end
    end
  end
end
