"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFailedShards = getFailedShards;
exports.getRootCause = getRootCause;
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

function getFailedShards(err) {
  var _errorInfo$caused_by;
  const errorInfo = err.attributes;
  const failedShards = (errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.failed_shards) || (errorInfo === null || errorInfo === void 0 ? void 0 : (_errorInfo$caused_by = errorInfo.caused_by) === null || _errorInfo$caused_by === void 0 ? void 0 : _errorInfo$caused_by.failed_shards);
  return failedShards ? failedShards[0] : undefined;
}
function getNestedCause(err) {
  const attr = err.attributes || err;
  const {
    type,
    reason,
    caused_by: causedBy
  } = attr;
  if (causedBy) {
    return getNestedCause(causedBy);
  }
  return {
    type,
    reason
  };
}
function getRootCause(err) {
  var _getFailedShards;
  // Give shard failures priority, then try to get the error navigating nested objects
  return ((_getFailedShards = getFailedShards(err)) === null || _getFailedShards === void 0 ? void 0 : _getFailedShards.reason) || getNestedCause(err);
}