"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.sampleAssetsRoutes = sampleAssetsRoutes;
var _configSchema = require("@kbn/config-schema");
var _constants_routes = require("../../common/constants_routes");
var _sample_assets = require("../lib/sample_assets");
var _write_assets = require("../lib/write_assets");
var _utils = require("./utils");
/*
 * 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.
 */

function sampleAssetsRoutes({
  router
}) {
  const SAMPLE_ASSETS_API_PATH = `${_constants_routes.ASSET_MANAGER_API_BASE}/assets/sample`;

  // GET sample assets
  router.get({
    path: SAMPLE_ASSETS_API_PATH,
    validate: {}
  }, async (context, req, res) => {
    return res.ok({
      body: {
        results: _sample_assets.sampleAssets
      }
    });
  });

  // POST sample assets
  router.post({
    path: SAMPLE_ASSETS_API_PATH,
    validate: {
      body: _configSchema.schema.nullable(_configSchema.schema.object({
        baseDateTime: _configSchema.schema.maybe(_configSchema.schema.oneOf([_configSchema.schema.string(), _configSchema.schema.number()])),
        excludeEans: _configSchema.schema.maybe(_configSchema.schema.arrayOf(_configSchema.schema.string())),
        refresh: _configSchema.schema.maybe(_configSchema.schema.oneOf([_configSchema.schema.boolean(), _configSchema.schema.literal('wait_for')]))
      }))
    }
  }, async (context, req, res) => {
    const {
      baseDateTime,
      excludeEans,
      refresh
    } = req.body || {};
    const parsed = baseDateTime === undefined ? undefined : new Date(baseDateTime);
    if ((parsed === null || parsed === void 0 ? void 0 : parsed.toString()) === 'Invalid Date') {
      return res.customError({
        statusCode: 400,
        body: {
          message: `${baseDateTime} is not a valid date time value`
        }
      });
    }
    const {
      elasticsearchClient
    } = await (0, _utils.getClientsFromContext)(context);
    const assetDocs = (0, _sample_assets.getSampleAssetDocs)({
      baseDateTime: parsed,
      excludeEans
    });
    try {
      const response = await (0, _write_assets.writeAssets)({
        elasticsearchClient,
        assetDocs,
        namespace: 'sample_data',
        refresh
      });
      if (response.errors) {
        return res.customError({
          statusCode: 500,
          body: {
            message: JSON.stringify(response.errors)
          }
        });
      }
      return res.ok({
        body: response
      });
    } catch (error) {
      return res.customError({
        statusCode: 500,
        body: {
          message: error.message || 'unknown error occurred while creating sample assets'
        }
      });
    }
  });

  // DELETE all sample assets
  router.delete({
    path: SAMPLE_ASSETS_API_PATH,
    validate: {}
  }, async (context, req, res) => {
    const {
      elasticsearchClient
    } = await (0, _utils.getClientsFromContext)(context);
    const sampleDataStreams = await elasticsearchClient.indices.getDataStream({
      name: 'assets-*-sample_data',
      expand_wildcards: 'all'
    });
    const deletedDataStreams = [];
    let errorWhileDeleting = null;
    const dataStreamsToDelete = sampleDataStreams.data_streams.map(ds => ds.name);
    for (let i = 0; i < dataStreamsToDelete.length; i++) {
      const dsName = dataStreamsToDelete[i];
      try {
        await elasticsearchClient.indices.deleteDataStream({
          name: dsName
        });
        deletedDataStreams.push(dsName);
      } catch (error) {
        errorWhileDeleting = typeof error.message === 'string' ? error.message : `Unknown error occurred while deleting sample data streams, at data stream name: ${dsName}`;
        break;
      }
    }
    if (!errorWhileDeleting && deletedDataStreams.length === dataStreamsToDelete.length) {
      return res.ok({
        body: {
          deleted: deletedDataStreams
        }
      });
    } else {
      return res.custom({
        statusCode: 500,
        body: {
          message: ['Not all found data streams were deleted', errorWhileDeleting].join(' - '),
          deleted: deletedDataStreams,
          matching: dataStreamsToDelete
        }
      });
    }
  });
}