"use strict";

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

/**
 * Global search provider adding an ES|QL and ESQL entry.
 * This is necessary because ES|QL is part of the Discover application.
 *
 * It navigates to Discover with a default query extracted from the default dataview
 */
const getESQLSearchProvider = (isESQLEnabled, uiCapabilities, data, locator) => ({
  id: 'esql',
  find: ({
    term = '',
    types,
    tags
  }) => {
    if (tags || types && !types.includes('application') || !locator || !isESQLEnabled) {
      return (0, _rxjs.of)([]);
    }
    return (0, _rxjs.from)(Promise.all([uiCapabilities, data]).then(async ([{
      navLinks
    }, {
      dataViews
    }]) => {
      if (!navLinks.discover) {
        return [];
      }
      const title = _i18n.i18n.translate('discover.globalSearch.esqlSearchTitle', {
        defaultMessage: 'Create ES|QL queries',
        description: 'ES|QL is a product name and should not be translated'
      });
      const defaultDataView = await dataViews.getDefaultDataView({
        displayErrors: false
      });
      if (!defaultDataView) {
        return [];
      }
      const params = {
        query: {
          esql: `from ${defaultDataView === null || defaultDataView === void 0 ? void 0 : defaultDataView.getIndexPattern()} | limit 10`
        },
        dataViewSpec: defaultDataView === null || defaultDataView === void 0 ? void 0 : defaultDataView.toSpec()
      };
      const discoverLocation = await (locator === null || locator === void 0 ? void 0 : locator.getLocation(params));
      term = term.toLowerCase();
      let score = 0;
      if (term === 'es|ql' || term === 'esql') {
        score = 100;
      } else if (term && ('es|ql'.includes(term) || 'esql'.includes(term))) {
        score = 90;
      }
      if (score === 0) return [];
      return [{
        id: 'esql',
        title,
        type: 'application',
        icon: 'logoKibana',
        meta: {
          categoryId: _public.DEFAULT_APP_CATEGORIES.kibana.id,
          categoryLabel: _public.DEFAULT_APP_CATEGORIES.kibana.label
        },
        score,
        url: `/app/${discoverLocation.app}${discoverLocation.path}`
      }];
    }));
  },
  getSearchableTypes: () => ['application']
});
exports.getESQLSearchProvider = getESQLSearchProvider;