"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getAssets = getAssets;
var _debug_log = require("../../common/debug_log");
var _constants = require("../constants");
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.
 */

async function getAssets({
  elasticsearchClient,
  size = 100,
  filters = {}
}) {
  // Maybe it makes the most sense to validate the filters here?
  (0, _debug_log.debug)('Get Assets Filters:', JSON.stringify(filters));
  const {
    from = 'now-24h',
    to = 'now'
  } = filters;
  const must = [];
  if (filters && Object.keys(filters).length > 0) {
    if (typeof filters.collectionVersion === 'number') {
      must.push({
        term: {
          ['asset.collection_version']: filters.collectionVersion
        }
      });
    }
    if ((0, _utils.isStringOrNonEmptyArray)(filters.type)) {
      must.push({
        terms: {
          ['asset.type']: Array.isArray(filters.type) ? filters.type : [filters.type]
        }
      });
    }
    if ((0, _utils.isStringOrNonEmptyArray)(filters.kind)) {
      must.push({
        terms: {
          ['asset.kind']: Array.isArray(filters.kind) ? filters.kind : [filters.kind]
        }
      });
    }
    if ((0, _utils.isStringOrNonEmptyArray)(filters.ean)) {
      must.push({
        terms: {
          ['asset.ean']: Array.isArray(filters.ean) ? filters.ean : [filters.ean]
        }
      });
    }
    if (filters.id) {
      must.push({
        term: {
          ['asset.id']: filters.id
        }
      });
    }
    if (filters.typeLike) {
      must.push({
        wildcard: {
          ['asset.type']: filters.typeLike
        }
      });
    }
    if (filters.kindLike) {
      must.push({
        wildcard: {
          ['asset.kind']: filters.kindLike
        }
      });
    }
    if (filters.eanLike) {
      must.push({
        wildcard: {
          ['asset.ean']: filters.eanLike
        }
      });
    }
  }
  const dsl = {
    index: _constants.ASSETS_INDEX_PREFIX + '*',
    size,
    query: {
      bool: {
        filter: [{
          range: {
            '@timestamp': {
              gte: from,
              lte: to
            }
          }
        }],
        must
      }
    },
    collapse: {
      field: 'asset.ean'
    },
    sort: {
      '@timestamp': {
        order: 'desc'
      }
    }
  };
  (0, _debug_log.debug)('Performing Get Assets Query', '\n\n', JSON.stringify(dsl, null, 2));
  const response = await elasticsearchClient.search(dsl);
  return response.hits.hits.map(hit => hit._source).filter(asset => !!asset);
}