# frozen_string_literal: true

require 'spec_helper'

describe Gitlab::Elasticsearch::Logs do
  let(:client) { Elasticsearch::Transport::Client }

  let(:es_message_1) { { timestamp: "2019-12-13T14:35:34.034Z", message: "10.8.2.1 - - [25/Oct/2019:08:03:22 UTC] \"GET / HTTP/1.1\" 200 13" } }
  let(:es_message_2) { { timestamp: "2019-12-13T14:35:35.034Z", message: "10.8.2.1 - - [27/Oct/2019:23:49:54 UTC] \"GET / HTTP/1.1\" 200 13" } }
  let(:es_message_3) { { timestamp: "2019-12-13T14:35:36.034Z", message: "10.8.2.1 - - [04/Nov/2019:23:09:24 UTC] \"GET / HTTP/1.1\" 200 13" } }
  let(:es_message_4) { { timestamp: "2019-12-13T14:35:37.034Z", message: "- -\u003e /" } }

  let(:es_response) { JSON.parse(fixture_file('lib/elasticsearch/logs_response.json', dir: 'ee')) }

  subject { described_class.new(client) }

  let(:namespace) { "autodevops-deploy-9-production" }
  let(:pod_name) { "production-6866bc8974-m4sk4" }
  let(:container_name) { "auto-deploy-app" }
  let(:search) { "foo +bar "}

  let(:body) { JSON.parse(fixture_file('lib/elasticsearch/query.json', dir: 'ee')) }
  let(:body_with_container) { JSON.parse(fixture_file('lib/elasticsearch/query_with_container.json', dir: 'ee')) }
  let(:body_with_search) { JSON.parse(fixture_file('lib/elasticsearch/query_with_search.json', dir: 'ee')) }

  RSpec::Matchers.define :a_hash_equal_to_json do |expected|
    match do |actual|
      actual.as_json == expected
    end
  end

  describe '#pod_logs' do
    it 'returns the logs as an array' do
      expect(client).to receive(:search).with(body: a_hash_equal_to_json(body)).and_return(es_response)

      result = subject.pod_logs(namespace, pod_name)
      expect(result).to eq([es_message_4, es_message_3, es_message_2, es_message_1])
    end

    it 'can further filter the logs by container name' do
      expect(client).to receive(:search).with(body: a_hash_equal_to_json(body_with_container)).and_return(es_response)

      result = subject.pod_logs(namespace, pod_name, container_name)
      expect(result).to eq([es_message_4, es_message_3, es_message_2, es_message_1])
    end

    it 'can further filter the logs by search' do
      expect(client).to receive(:search).with(body: a_hash_equal_to_json(body_with_search)).and_return(es_response)

      result = subject.pod_logs(namespace, pod_name, nil, search)
      expect(result).to eq([es_message_4, es_message_3, es_message_2, es_message_1])
    end
  end
end
