require 'spec_helper'
require 'webmock/rspec'

describe OAuthSession do
  let(:session) { Fabricate :roqua_core_api_oauth_session }
  let(:response) { double('response', code: 201, parsed_response: 'some_response') }

  describe '#initialize' do
    it 'sets the access_token instance variable' do
      session = Roqua::CoreApi.oauth_session access_token: 'some_access_token'
      expect(session.access_token).to eq('some_access_token')
    end

    it 'allows to override the core_site variable' do
      session = Roqua::CoreApi.oauth_session access_token: 'some_access_token', core_site: 'some_core_site'
      expect(session.core_site).to eq('some_core_site')
    end

    it 'defaults the AuthSession core_site CORE_SITE env variable default value' do
      original_env_core_site = ENV['CORE_SITE']
      ENV['CORE_SITE'] = 'some_env_core_site'
      session = Roqua::CoreApi.oauth_session access_token: 'some_access_token'
      ENV['CORE_SITE'] = original_env_core_site
      expect(session.core_site).to eq('some_env_core_site')
    end
  end

  describe '#logout_url' do
    it 'returns the oauth session destroy url with an escaped redirect_to parameter' do
      expect(session.logout_url return_to: 'some redirect to')
        .to eq('http://core.dev/session/destroy?token=some_access_token&return_to=some+redirect+to')
    end
  end

  describe 'headers' do
    it 'sets the Authorization header' do
      expect(HTTParty).to receive(:get).with(an_instance_of(String),
                                             headers: {"Authorization" => "Bearer some_access_token"},
                                             query: {},
                                             basic_auth: nil,
                                             timeout: nil).and_return(response)
      session.get 'some_path'
    end
  end

  describe '#access_denied' do
    it 'raises a no_session error when response is 401 with a no_session response' do
      stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return(
        status: 401,
        body: '{ "no_session": true }',
        headers: { 'Content-Type' => 'application/json' })
      expect { session.get '/some_path' }.to raise_error(NoSession)
    end

    it 'raises a unauthorized error when response is 401 without a no_session response' do
      stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return(
        status: 401,
        body: '',
        headers: { 'Content-Type' => 'application/json' })
      expect { session.get '/some_path' }.to raise_error(Unauthorized)
    end
  end
end