"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getServiceAgent = getServiceAgent;
var _server = require("@kbn/observability-plugin/server");
var _common = require("@kbn/observability-plugin/common");
var _apm = require("../../../common/es_fields/apm");
var _serverless = require("../../../common/serverless");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

async function getServiceAgent({
  serviceName,
  apmEventClient,
  start,
  end
}) {
  var _cloud$service, _service$runtime;
  const params = {
    terminate_after: 1,
    apm: {
      events: [_common.ProcessorEvent.error, _common.ProcessorEvent.transaction, _common.ProcessorEvent.metric]
    },
    body: {
      track_total_hits: 1,
      size: 1,
      _source: [_apm.AGENT_NAME, _apm.SERVICE_RUNTIME_NAME, _apm.CLOUD_PROVIDER, _apm.CLOUD_SERVICE_NAME],
      query: {
        bool: {
          filter: [{
            term: {
              [_apm.SERVICE_NAME]: serviceName
            }
          }, ...(0, _server.rangeQuery)(start, end), {
            exists: {
              field: _apm.AGENT_NAME
            }
          }],
          should: [{
            exists: {
              field: _apm.SERVICE_RUNTIME_NAME
            }
          }, {
            exists: {
              field: _apm.CLOUD_PROVIDER
            }
          }, {
            exists: {
              field: _apm.CLOUD_SERVICE_NAME
            }
          }]
        }
      },
      sort: {
        _score: {
          order: 'desc'
        }
      }
    }
  };
  const response = await apmEventClient.search('get_service_agent_name', params);
  if (response.hits.total.value === 0) {
    return {};
  }
  const {
    agent,
    service,
    cloud
  } = response.hits.hits[0]._source;
  const serverlessType = (0, _serverless.getServerlessTypeFromCloudData)(cloud === null || cloud === void 0 ? void 0 : cloud.provider, cloud === null || cloud === void 0 ? void 0 : (_cloud$service = cloud.service) === null || _cloud$service === void 0 ? void 0 : _cloud$service.name);
  return {
    agentName: agent === null || agent === void 0 ? void 0 : agent.name,
    runtimeName: service === null || service === void 0 ? void 0 : (_service$runtime = service.runtime) === null || _service$runtime === void 0 ? void 0 : _service$runtime.name,
    serverlessType
  };
}