module History
  describe ReportsController do
    include_context 'mocked permissions'

    describe 'index' do
      let(:action) { :index }
      let(:permission) { 'history_gdpr_reports' }
      let(:requester) { 'cool_ldap_login' }

      context 'with permissions' do
        include_context 'an authorized user'

        it 'sends requester' do
          expect(History::Report).to receive(:list_reports)
            .with(ActionController::Parameters.new({
              requester: requester,
            }).permit(:requester))
            .and_return(
              {
                :items => []
              }
            )

          get action, params: { search: { requester: requester } }
          expect(flash[:error]).to be_nil
        end

        it 'redirects user with service failed error' do
          expect(History::Report).to receive(:list_reports).and_raise StandardError.new "service failed"
          get action, params: {}
          expect(response).to redirect_to(history_reports_path)
          expect(flash[:error]).to eql("service failed")
        end
      end
    end

    describe 'create' do
      let(:action) { :create }
      let(:permission) { 'history_gdpr_reports' }
      let(:requester) { 'cool_ldap_login' }
      let(:user_id) { 'my-user-id' }
      let(:reports) { [] }

      context 'with permissions' do
        include_context 'an authorized user'

        it 'creates report' do
          stub_request(:post, "#{Settings.history.endpoint}/v1/authed/audits").to_return(:status => 200, :body => "", :headers => {})
          expect(History::Report).to receive(:request_report)
            .with(
              user_id,
              requester
            )
          post action, params: { search: { user_id: user_id } }
          expect(response).to redirect_to(history_reports_path)
          expect(flash[:success]).to eql("Successfully requested report")
        end

        it 'redirect user with error when request fails' do
          expect(History::Report).to receive(:request_report).and_raise StandardError.new "service failed"
          post action, params: {}
          expect(response).to redirect_to(history_reports_path)
          expect(flash[:error]).to eql("service failed")
        end
      end

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

        it 'redirects the user and displays an error' do
          get action, params: {}
        end
      end
    end
  end
end
