"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SearchAuthorizeLogic = void 0;
var _kea = require("kea");
var _constants = require("../../../../../common/constants");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _query_params = require("../../../shared/query_params");
var _oauth_authorize_logic = require("../oauth_authorize/oauth_authorize_logic");
/*
 * 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 SearchAuthorizeLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'workplace_search', 'search_authorize_logic'],
  actions: {
    setServerProps: serverProps => serverProps,
    initializeSearchAuth: (searchOAuth, search) => [searchOAuth, search],
    authorizeSearch: null,
    setRedirectNotPending: null
  },
  reducers: {
    redirectPending: [true, {
      setRedirectNotPending: () => false
    }],
    cachedPreAuth: [{}, {
      setServerProps: (_, serverProps) => (0, _oauth_authorize_logic.transformServerPreAuth)(serverProps)
    }]
  },
  listeners: ({
    actions,
    values
  }) => ({
    initializeSearchAuth: async ([searchOAuth, search]) => {
      (0, _flash_messages.clearFlashMessages)();
      const {
        http
      } = _http.HttpLogic.values;
      const {
        state
      } = (0, _query_params.parseQueryParams)(search);
      const query = {
        client_id: searchOAuth.clientId,
        response_type: 'code',
        redirect_uri: searchOAuth.redirectUrl,
        scope: 'default_search',
        state
      };
      try {
        const response = await http.get(_oauth_authorize_logic.oauthAuthorizeRoute, {
          query
        });
        if (response.status === 'redirect') {
          window.location.replace(response.redirect_uri);
        } else {
          actions.setServerProps(response);
        }
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
        actions.setRedirectNotPending();
      }
    },
    setServerProps: () => {
      actions.authorizeSearch();
    },
    authorizeSearch: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        cachedPreAuth
      } = values;
      try {
        const response = await http.post(_oauth_authorize_logic.oauthAuthorizeRoute, {
          body: JSON.stringify({
            client_id: cachedPreAuth.clientId,
            response_type: cachedPreAuth.responseType,
            redirect_uri: cachedPreAuth.redirectUri,
            scope: cachedPreAuth.rawScopes,
            state: cachedPreAuth.state
          }),
          headers: _constants.JSON_HEADER
        });
        window.location.replace(response.redirect_uri);
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
        actions.setRedirectNotPending();
      }
    }
  })
});
exports.SearchAuthorizeLogic = SearchAuthorizeLogic;