"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TelemetryLogic = void 0;
var _kea = require("kea");
var _constants = require("../../../../common/constants");
var _http = require("../http");
/*
 * 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 TelemetryLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'telemetry_logic'],
  actions: {
    sendTelemetry: ({
      action,
      metric,
      product
    }) => ({
      action,
      metric,
      product
    }),
    sendEnterpriseSearchTelemetry: ({
      action,
      metric
    }) => ({
      action,
      metric
    }),
    sendAppSearchTelemetry: ({
      action,
      metric
    }) => ({
      action,
      metric
    }),
    sendWorkplaceSearchTelemetry: ({
      action,
      metric
    }) => ({
      action,
      metric
    })
  },
  listeners: ({
    actions
  }) => ({
    sendTelemetry: async ({
      action,
      metric,
      product
    }) => {
      const {
        http
      } = _http.HttpLogic.values;
      try {
        const body = JSON.stringify({
          product,
          action,
          metric
        });
        await http.put('/internal/enterprise_search/stats', {
          headers: _constants.JSON_HEADER,
          body
        });
      } catch (error) {
        throw new Error('Unable to send telemetry');
      }
    },
    sendEnterpriseSearchTelemetry: ({
      action,
      metric
    }) => actions.sendTelemetry({
      action,
      metric,
      product: 'enterprise_search'
    }),
    sendAppSearchTelemetry: ({
      action,
      metric
    }) => actions.sendTelemetry({
      action,
      metric,
      product: 'app_search'
    }),
    sendWorkplaceSearchTelemetry: ({
      action,
      metric
    }) => actions.sendTelemetry({
      action,
      metric,
      product: 'workplace_search'
    })
  })
});
exports.TelemetryLogic = TelemetryLogic;