require 'spec_helper'
require 'webmock/rspec'

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

  describe '#initialize' do
    it 'sets the core_site instance attribute' do
      session = AuthSession.new core_site: 'some_core_site'
      expect(session.core_site).to eq('some_core_site')
    end

    it 'defaults the core_site to the CORE_SITE env variable' do
      original_env_core_site = ENV['CORE_SITE']
      ENV['CORE_SITE'] = 'some_env_core_site'
      session = AuthSession.new
      ENV['CORE_SITE'] = original_env_core_site
      expect(session.core_site).to eq('some_env_core_site')
    end

    it 'sets the default timeout' do
      session = AuthSession.new timeout: 30
      expect(session.default_timeout).to eq 30
    end

    it 'defaults the default timeout to nil' do
      session = AuthSession.new
      expect(session.default_timeout).to be_nil
    end
  end

  describe '#get' do
    it 'performs a get request' do
      allow(session).to receive(:basic_auth).and_return(username: 'some_username', password: 'some_password')
      allow(session).to receive(:headers).and_return(some: 'header')
      expect(HTTParty).to receive(:get).with('http://core.roqua.eu/api/v1/some_path.json',
                                             query: {some: 'param'},
                                             headers: {some: 'header'},
                                             basic_auth: {username: 'some_username', password: 'some_password'},
                                             timeout: nil)
                                       .and_return(response)
      session.get '/some_path', some: 'param'
    end

    it 'returns the response on sucess status' do
      stub_request(:get, 'http://core.roqua.eu/api/v1/some_path.json?').to_return(
        status: 201,
        body: '{ "success": true }',
        headers: { 'Content-Type' => 'application/json' })
      expect(session.get('/some_path')['success']).to be_truthy
    end

    it 'returns the response on a 422 status' do
      stub_request(:get, 'http://core.roqua.eu/api/v1/some_path.json?').to_return(
        status: 422,
        body: '{ "errors": { "column": ["wrong"] } }',
        headers: { 'Content-Type' => 'application/json' })
      expect(session.get('/some_path')['errors']['column']).to eq ["wrong"]
    end

    it 'throws an error if the reponse is not within the 200 range' do
      allow(response).to receive(:code).and_return(500)
      allow(HTTParty).to receive(:get).and_return(response)
      expect { session.get '/some_path' }.to raise_error(RuntimeError, 'some_response')
    end

    it 'returns the response' do
      allow(HTTParty).to receive(:get).and_return(response)
      expect(session.get '/some_path').to eq(response)
    end
  end
end