"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getIndirectlyRelatedAssets = getIndirectlyRelatedAssets;
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 getIndirectlyRelatedAssets({
  elasticsearchClient,
  size = 100,
  from = 'now-24h',
  to = 'now',
  ean,
  excludeEans,
  relation,
  kind
}) {
  const relationField = relationToIndirectField(relation);
  const must = [{
    terms: {
      [relationField]: [ean]
    }
  }];
  if ((0, _utils.isStringOrNonEmptyArray)(kind)) {
    must.push({
      terms: {
        ['asset.kind']: Array.isArray(kind) ? kind : [kind]
      }
    });
  }
  const mustNot = excludeEans && excludeEans.length ? [{
    terms: {
      'asset.ean': excludeEans
    }
  }] : [];
  const dsl = {
    index: _constants.ASSETS_INDEX_PREFIX + '*',
    size,
    query: {
      bool: {
        filter: [{
          range: {
            '@timestamp': {
              gte: from,
              lte: to
            }
          }
        }],
        must,
        must_not: mustNot
      }
    },
    collapse: {
      field: 'asset.ean'
    },
    sort: {
      '@timestamp': {
        order: 'desc'
      }
    }
  };
  (0, _debug_log.debug)('Performing Indirectly Related Asset 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);
}
function relationToIndirectField(relation) {
  if (relation === 'ancestors') {
    return 'asset.children';
  } else if (relation === 'descendants') {
    return 'asset.parents';
  } else {
    return 'asset.references';
  }
}