"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaultApiToken = exports.ApiKeysLogic = void 0;
var _kea = require("kea");
var _constants = require("../../../shared/constants");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _table_pagination = require("../../../shared/table_pagination");
var _constants2 = require("./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 formatApiName = rawName => rawName.trim().replace(/[^a-zA-Z0-9]+/g, '-') // Replace all special/non-alphanumerical characters with dashes
.replace(/^[-]+|[-]+$/g, '') // Strip all leading and trailing dashes
.toLowerCase();
const defaultApiToken = {
  name: ''
};
exports.defaultApiToken = defaultApiToken;
const ApiKeysLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'workplace_search', 'api_keys_logic'],
  actions: () => ({
    onApiTokenCreateSuccess: apiToken => apiToken,
    onApiTokenError: formErrors => formErrors,
    setApiKeysData: (meta, apiTokens) => ({
      meta,
      apiTokens
    }),
    setNameInputBlurred: nameInputBlurred => nameInputBlurred,
    setApiKeyName: name => name,
    showApiKeyForm: true,
    hideApiKeyForm: false,
    resetApiKeys: false,
    fetchApiKeys: true,
    onPaginate: newPageIndex => ({
      newPageIndex
    }),
    deleteApiKey: true,
    stageTokenNameForDeletion: tokenName => tokenName,
    hideDeleteModal: true,
    onApiFormSubmit: () => null
  }),
  reducers: () => ({
    dataLoading: [true, {
      setApiKeysData: () => false
    }],
    apiTokens: [[], {
      setApiKeysData: (_, {
        apiTokens
      }) => apiTokens,
      onApiTokenCreateSuccess: (apiTokens, apiToken) => [...apiTokens, apiToken]
    }],
    meta: [_constants.DEFAULT_META, {
      setApiKeysData: (_, {
        meta
      }) => meta,
      onPaginate: (state, {
        newPageIndex
      }) => (0, _table_pagination.updateMetaPageIndex)(state, newPageIndex)
    }],
    nameInputBlurred: [false, {
      setNameInputBlurred: (_, nameInputBlurred) => nameInputBlurred
    }],
    activeApiToken: [defaultApiToken, {
      onApiTokenCreateSuccess: () => defaultApiToken,
      hideApiKeyForm: () => defaultApiToken,
      setApiKeyName: (activeApiToken, name) => ({
        ...activeApiToken,
        name: formatApiName(name)
      })
    }],
    activeApiTokenRawName: ['', {
      setApiKeyName: (_, activeApiTokenRawName) => activeApiTokenRawName,
      hideApiKeyForm: () => '',
      onApiTokenCreateSuccess: () => ''
    }],
    apiKeyFormVisible: [false, {
      showApiKeyForm: () => true,
      hideApiKeyForm: () => false,
      onApiTokenCreateSuccess: () => false
    }],
    deleteModalVisible: [false, {
      stageTokenNameForDeletion: () => true,
      hideDeleteModal: () => false
    }],
    apiTokenNameToDelete: ['', {
      stageTokenNameForDeletion: (_, tokenName) => tokenName,
      hideDeleteModal: () => ''
    }],
    formErrors: [[], {
      onApiTokenError: (_, formErrors) => formErrors,
      onApiTokenCreateSuccess: () => [],
      showApiKeyForm: () => [],
      resetApiKeys: () => []
    }]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    showApiKeyForm: () => {
      (0, _flash_messages.clearFlashMessages)();
    },
    fetchApiKeys: async () => {
      try {
        const {
          http
        } = _http.HttpLogic.values;
        const {
          meta
        } = values;
        const query = {
          'page[current]': meta.page.current,
          'page[size]': meta.page.size
        };
        const response = await http.get('/internal/workplace_search/api_keys', {
          query
        });
        actions.setApiKeysData(response.meta, response.results);
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    deleteApiKey: async () => {
      const {
        apiTokenNameToDelete
      } = values;
      try {
        const {
          http
        } = _http.HttpLogic.values;
        await http.delete(`/internal/workplace_search/api_keys/${apiTokenNameToDelete}`);
        actions.fetchApiKeys();
        (0, _flash_messages.flashSuccessToast)((0, _constants2.DELETE_MESSAGE)(apiTokenNameToDelete));
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      } finally {
        actions.hideDeleteModal();
      }
    },
    onApiFormSubmit: async () => {
      const {
        name
      } = values.activeApiToken;
      const data = {
        name
      };
      try {
        const {
          http
        } = _http.HttpLogic.values;
        const body = JSON.stringify(data);
        const response = await http.post('/internal/workplace_search/api_keys', {
          body
        });
        actions.onApiTokenCreateSuccess(response);
        (0, _flash_messages.flashSuccessToast)((0, _constants2.CREATE_MESSAGE)(name));
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    }
  })
});
exports.ApiKeysLogic = ApiKeysLogic;