"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getErrorSampleDetails = getErrorSampleDetails;
var _server = require("@kbn/observability-plugin/server");
var _common = require("@kbn/observability-plugin/common");
var _apm = require("../../../../common/es_fields/apm");
var _environment_query = require("../../../../common/utils/environment_query");
var _get_transaction = require("../../transactions/get_transaction");
/*
 * 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 getErrorSampleDetails({
  environment,
  kuery,
  serviceName,
  errorId,
  apmEventClient,
  start,
  end
}) {
  var _resp$hits$hits$, _error$transaction, _error$trace;
  const params = {
    apm: {
      events: [_common.ProcessorEvent.error]
    },
    body: {
      track_total_hits: false,
      size: 1,
      query: {
        bool: {
          filter: [{
            term: {
              [_apm.SERVICE_NAME]: serviceName
            }
          }, {
            term: {
              [_apm.ERROR_ID]: errorId
            }
          }, ...(0, _server.rangeQuery)(start, end), ...(0, _environment_query.environmentQuery)(environment), ...(0, _server.kqlQuery)(kuery)]
        }
      }
    }
  };
  const resp = await apmEventClient.search('get_error_sample_details', params);
  const error = (_resp$hits$hits$ = resp.hits.hits[0]) === null || _resp$hits$hits$ === void 0 ? void 0 : _resp$hits$hits$._source;
  const transactionId = error === null || error === void 0 ? void 0 : (_error$transaction = error.transaction) === null || _error$transaction === void 0 ? void 0 : _error$transaction.id;
  const traceId = error === null || error === void 0 ? void 0 : (_error$trace = error.trace) === null || _error$trace === void 0 ? void 0 : _error$trace.id;
  let transaction;
  if (transactionId && traceId) {
    transaction = await (0, _get_transaction.getTransaction)({
      transactionId,
      traceId,
      apmEventClient,
      start,
      end
    });
  }
  return {
    transaction,
    error
  };
}