"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.parseEsError = exports.getErrorCodeFromErrorReason = void 0;
var _i18n = require("@kbn/i18n");
/*
 * 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.
 */

const getErrorCodeFromErrorReason = (reason = '') => {
  if (reason.includes('Cannot cast from')) {
    return 'CAST_ERROR';
  }
  return 'UNKNOWN';
};
exports.getErrorCodeFromErrorReason = getErrorCodeFromErrorReason;
const parseEsError = scriptError => {
  var _scriptError$caused_b, _scriptError$position, _scriptError$script_s, _reason;
  let reason = (_scriptError$caused_b = scriptError.caused_by) === null || _scriptError$caused_b === void 0 ? void 0 : _scriptError$caused_b.reason;
  const errorCode = getErrorCodeFromErrorReason(reason);
  if (errorCode === 'CAST_ERROR') {
    // Help the user as he might have forgot to change the runtime type
    reason = `${reason} ${_i18n.i18n.translate('indexPatternFieldEditor.editor.form.scriptEditor.castErrorMessage', {
      defaultMessage: 'Verify that you have correctly set the runtime field type.'
    })}`;
  }
  return {
    message: _i18n.i18n.translate('indexPatternFieldEditor.editor.form.scriptEditor.compileErrorMessage', {
      defaultMessage: 'Error compiling the painless script'
    }),
    position: (_scriptError$position = scriptError.position) !== null && _scriptError$position !== void 0 ? _scriptError$position : null,
    scriptStack: (_scriptError$script_s = scriptError.script_stack) !== null && _scriptError$script_s !== void 0 ? _scriptError$script_s : [],
    reason: (_reason = reason) !== null && _reason !== void 0 ? _reason : null,
    code: errorCode
  };
};
exports.parseEsError = parseEsError;