"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SampleEngineCreationCtaLogic = void 0;
var _reactRouterDom = require("react-router-dom");
var _kea = require("kea");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _kibana = require("../../../shared/kibana");
var _routes = require("../../routes");
var _constants = require("../engine_creation/constants");
/*
 * 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 SampleEngineCreationCtaLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'sample_engine_cta_logic'],
  actions: {
    createSampleEngine: true,
    onSampleEngineCreationSuccess: true,
    onSampleEngineCreationFailure: true
  },
  reducers: {
    isLoading: [false, {
      createSampleEngine: () => true,
      onSampleEngineCreationSuccess: () => false,
      onSampleEngineCreationFailure: () => false
    }]
  },
  listeners: ({
    actions
  }) => ({
    createSampleEngine: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const body = JSON.stringify({
        seed_sample_engine: true
      });
      try {
        await http.post('/internal/app_search/onboarding_complete', {
          body
        });
        actions.onSampleEngineCreationSuccess();
      } catch (e) {
        actions.onSampleEngineCreationFailure();
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    onSampleEngineCreationSuccess: () => {
      const {
        navigateToUrl
      } = _kibana.KibanaLogic.values;
      const enginePath = (0, _reactRouterDom.generatePath)(_routes.ENGINE_PATH, {
        engineName: 'national-parks-demo'
      });
      (0, _flash_messages.flashSuccessToast)((0, _constants.ENGINE_CREATION_SUCCESS_MESSAGE)('national-parks-demo'));
      navigateToUrl(enginePath);
    }
  })
});
exports.SampleEngineCreationCtaLogic = SampleEngineCreationCtaLogic;