require 'rails_helper'

RSpec.describe Attachments::HostedImagesController do

  include_context 'mocked permissions'

  let(:permission) { 'admin_image_upload' }

  describe 'index' do
    context 'with views' do
      include_context 'stubbed spade requests'
      let(:event_name) { 'admin_panel_page_view' }
      let(:user_properties) { {'ldap' => admin_account.ldap_login, 'client_time' => Time.now.to_f, 'user_agent' => request.headers['User-Agent'], 'ip' => '0.0.0.0', 'session_id' => request.session.id} }
      let(:event_properties) { { 'url' => 'http://test.host/attachments/hosted_images'}.merge(user_properties) }
      let(:spade_args) { {'event' => event_name, 'properties' => event_properties} }

      before do
        travel_to Time.local('2019')
      end

      after do
        travel_back
      end

      it 'sends a request to spade' do
        expected_data = Base64.encode64({'event' => event_name, 'properties' => event_properties}.to_json)
        expect_any_instance_of(Faraday::Connection).to receive(:post).with('/track', {:data => expected_data}).and_return(:status => 204, :body => "", :headers => {})
        get :index
      end
    end

    describe 'permissions' do
      let(:action) { :index }

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

        before do
          get action
        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 action
        end

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

  end

  describe 'create' do
    describe 'permissions' do
      let(:action) { :create }

      context 'a user with appropriate permissions' do
        include_context 'an authorized user'
        include_context 'it creates any tracking call'

        before do
          expect_any_instance_of(Attachments::HostedImage).to receive(:save).and_return(true)
          post action, :params => {:attachments_hosted_image => {:filename => 'foo', :data => 'bar'}}
        end

        it_behaves_like 'it returns a success response'
      end

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

        before do
          post action, :params => {:attachments_hosted_image => {:filename => 'foo', :data => 'bar'}}
        end

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