"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.addAnalyticsCollection = void 0;
var _error_codes = require("../../../common/types/error_codes");
var _identify_exceptions = require("../../utils/identify_exceptions");
var _fetch_analytics_collection = require("./fetch_analytics_collection");
/*
 * 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 createAnalyticsCollection = async (client, name) => await client.asCurrentUser.searchApplication.putBehavioralAnalytics({
  name
});
const createDataView = async (dataViewsService, analyticsCollection) => {
  return dataViewsService.createAndSave({
    allowNoIndex: true,
    name: `behavioral_analytics.events-${analyticsCollection.name}`,
    timeFieldName: '@timestamp',
    title: analyticsCollection.events_datastream
  }, true);
};
const addAnalyticsCollection = async (client, dataViewsService, name) => {
  try {
    await createAnalyticsCollection(client, name);
  } catch (error) {
    if ((0, _identify_exceptions.isResourceAlreadyExistsException)(error)) {
      throw new Error(_error_codes.ErrorCode.ANALYTICS_COLLECTION_ALREADY_EXISTS);
    }
  }
  const analyticsCollections = await (0, _fetch_analytics_collection.fetchAnalyticsCollections)(client, name);
  const analyticsCollection = analyticsCollections[0];
  await createDataView(dataViewsService, analyticsCollection);
  return analyticsCollection;
};
exports.addAnalyticsCollection = addAnalyticsCollection;