"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CurationSuggestionLogic = void 0;
var _kea = require("kea");
var _i18n = require("@kbn/i18n");
var _flash_messages = require("../../../../../shared/flash_messages");
var _http = require("../../../../../shared/http");
var _kibana = require("../../../../../shared/kibana");
var _routes = require("../../../../routes");
var _engine = require("../../../engine");
/*
 * 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.
 */

const CurationSuggestionLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'curations', 'suggestion_logic'],
  actions: () => ({
    loadSuggestion: true,
    onSuggestionLoaded: ({
      suggestion
    }) => ({
      suggestion
    }),
    acceptSuggestion: true,
    acceptAndAutomateSuggestion: true,
    rejectSuggestion: true,
    rejectAndDisableSuggestion: true
  }),
  reducers: () => ({
    dataLoading: [true, {
      loadSuggestion: () => true,
      onSuggestionLoaded: () => false
    }],
    suggestion: [null, {
      onSuggestionLoaded: (_, {
        suggestion
      }) => suggestion
    }]
  }),
  listeners: ({
    actions,
    values,
    props
  }) => ({
    loadSuggestion: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const suggestionResponse = await http.get(`/internal/app_search/engines/${engineName}/adaptive_relevance/suggestions/${props.query}`, {
          query: {
            type: 'curation'
          }
        });

        // We pull the `organic` and `promoted` fields up to the main body of the suggestion,
        // out of the nested `suggestion` field on the response
        const {
          suggestion,
          ...baseSuggestion
        } = suggestionResponse;
        const suggestionData = {
          ...baseSuggestion,
          promoted: suggestion.promoted,
          organic: suggestion.organic
        };
        actions.onSuggestionLoaded({
          suggestion: suggestionData
        });
      } catch (e) {
        var _e$response;
        if (((_e$response = e.response) === null || _e$response === void 0 ? void 0 : _e$response.status) === 404) {
          const message = _i18n.i18n.translate('xpack.enterpriseSearch.appSearch.engine.curations.suggestedCuration.notFoundError', {
            defaultMessage: 'Could not find suggestion, it may have already been applied or rejected.'
          });
          (0, _flash_messages.setQueuedErrorMessage)(message);
          _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATIONS_PATH));
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    acceptSuggestion: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        suggestion
      } = values;
      if (suggestion.operation === 'delete') {
        const confirmed = await confirmDialog('Are you sure you want to delete this curation?');
        if (!confirmed) return;
      }
      try {
        const updatedSuggestion = await updateSuggestion(http, engineName, suggestion.query, 'applied');
        (0, _flash_messages.setQueuedSuccessMessage)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.engine.curations.suggestedCuration.successfullyAppliedMessage', {
          defaultMessage: 'Suggestion was successfully applied.'
        }));
        if (suggestion.operation === 'delete') {
          // Because if a curation is deleted, there will be no curation detail page to navigate to afterwards.
          _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATIONS_PATH));
        } else {
          _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATION_PATH, {
            curationId: updatedSuggestion.curation_id
          }));
        }
      } catch (e) {
        if (e.message) {
          (0, _flash_messages.setErrorMessage)(e.message);
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    acceptAndAutomateSuggestion: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        suggestion
      } = values;
      if (suggestion.operation === 'delete') {
        const confirmed = await confirmDialog('Are you sure you want to delete this curation?');
        if (!confirmed) return;
      }
      try {
        const updatedSuggestion = await updateSuggestion(http, engineName, suggestion.query, 'automated');
        (0, _flash_messages.setQueuedSuccessMessage)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.engine.curations.suggestedCuration.successfullyAutomatedMessage', {
          defaultMessage: 'Suggestion was successfully applied and all future suggestions for the query "{query}" will be automatically applied.',
          values: {
            query: suggestion.query
          }
        }));
        if (suggestion.operation === 'delete') {
          // Because if a curation is deleted, there will be no curation detail page to navigate to afterwards.
          _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATIONS_PATH));
        } else {
          _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATION_PATH, {
            curationId: updatedSuggestion.curation_id
          }));
        }
      } catch (e) {
        if (e.message) {
          (0, _flash_messages.setErrorMessage)(e.message);
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    rejectSuggestion: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        suggestion
      } = values;
      try {
        await updateSuggestion(http, engineName, suggestion.query, 'rejected');
        (0, _flash_messages.setQueuedSuccessMessage)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.engine.curations.suggestedCuration.successfullyRejectedMessage', {
          defaultMessage: 'Suggestion was successfully rejected.'
        }));
        _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATIONS_PATH));
      } catch (e) {
        if (e.message) {
          (0, _flash_messages.setErrorMessage)(e.message);
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    rejectAndDisableSuggestion: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        suggestion
      } = values;
      try {
        await updateSuggestion(http, engineName, suggestion.query, 'disabled');
        (0, _flash_messages.setQueuedSuccessMessage)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.engine.curations.suggestedCuration.successfullyDisabledMessage', {
          defaultMessage: 'Suggestion was successfully rejected and you will no longer receive suggestions for the query "{query}".',
          values: {
            query: suggestion.query
          }
        }));
        _kibana.KibanaLogic.values.navigateToUrl((0, _engine.generateEnginePath)(_routes.ENGINE_CURATIONS_PATH));
      } catch (e) {
        if (e.message) {
          (0, _flash_messages.setErrorMessage)(e.message);
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    }
  })
});
exports.CurationSuggestionLogic = CurationSuggestionLogic;
const updateSuggestion = async (http, engineName, query, status) => {
  const response = await http.put(`/internal/app_search/engines/${engineName}/adaptive_relevance/suggestions`, {
    body: JSON.stringify([{
      query,
      type: 'curation',
      status
    }])
  });
  if (response.results[0].hasOwnProperty('error')) {
    throw new Error(response.results[0].error);
  }
  return response.results[0];
};
const confirmDialog = msg => {
  return new Promise(function (resolve) {
    const confirmed = window.confirm(msg);
    return resolve(confirmed);
  });
};