require 'test_helper'
require 'cubert/client'

class CubertRequestLogsServiceTest < ActiveSupport::TestCase
  def setup
    WebMock.disable_net_connect!(allow: ['cubert', /172\./, /127\./])
    ThreeScale::Core::Service.stubs(:set_log_bucket).with do |service_id, bucket_id|
      service_id.is_a?(Integer) && bucket_id.is_a?(String)
    end
    ThreeScale::Core::Service.stubs(:clear_log_bucket)
  end

  def teardown
    WebMock.disable_net_connect!
  end

  def test_getting_log_list
    setup_for_instance_methods

    @cubert_service.store_logs [@log1, @log2]
    log_requests = @cubert_service.get_list
    assert_equal 1, log_requests.size

    log = log_requests.first
    assert_equal 2, log.application_id
    assert_equal 2010, log.timestamp.year
    assert_equal 'req', log.request
    assert_equal 'resp', log.response
    assert_equal 200, log.code
  end

  def test_get_list_is_empty
    cubert_service = CubertRequestLogsService.new(nil)

    list = cubert_service.get_list
    assert list.empty?
  end

  def test_store_logs_single_element
    setup_for_instance_methods

    @cubert_service.store_logs @log1
    log_requests = @cubert_service.get_list
    assert_equal 1, log_requests.size
  end

  def test_enabling_and_disabling
    setup_for_class_methods
    CubertRequestLogsService.enable @service.id
    assert_not_nil @service.reload.cubert_info.bucket_id

    CubertRequestLogsService.disable @service.id
    assert_nil @service.reload.cubert_info
  end

  test 'enabling does nothing without config' do
    Rails.configuration.cubert.stubs(:server).returns(enabled: false)

    refute CubertRequestLogsService.enable 42
    refute CubertRequestLogsService.disable 42
  end

  test 'enabled?' do
    Rails.configuration.cubert.stubs(server: {enabled: false})
    refute CubertRequestLogsService.new(nil).enabled?
    assert CubertRequestLogsService.new(nil).disabled?
  end

  test 'getting log list when cubert is disabled' do
    setup_for_instance_methods
    CubertRequestLogsService.stubs(enabled?: false)

    list = @cubert_service.get_list
    assert list.empty?
  end

  private

  def create_cubert_bucket
    CubertRequestLogsService.new(nil).connection.create_bucket.id
  end

  def setup_for_class_methods
    skip 'cubert integration does not work now'

    @service = Factory.create :service
  end

  def setup_for_instance_methods
    skip 'cubert integration does not work now'

    @log1 = { service_id: 1, application_id: 2, timestamp: '2010-04-01 12:34',
      log: { request: 'req', response: 'resp', code: 200 }}
    @log2 = { service_id: 3, application_id: 4, timestamp: '2012-12-10 23:45',
      log: { request: 'req', response: 'resp', code: 200 }}

    cubert_info = ServiceCubertInfo.new
    cubert_info.bucket_id = create_cubert_bucket
    cubert_info.service = Factory.build(:service, id: 1)

    @cubert_service = CubertRequestLogsService.new(cubert_info)
  end
end
