"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.processCategoryResults = processCategoryResults;
var _lodash = require("lodash");
/*
 * 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 processCategoryResults(result, field, unwrap) {
  const sparkLinesPerCategory = {};
  const {
    aggregations
  } = result.rawResponse;
  if (aggregations === undefined) {
    throw new Error('processCategoryResults failed, did not return aggregations.');
  }
  const {
    categories: {
      buckets
    }
  } = unwrap(aggregations);
  const categories = buckets.map(b => {
    sparkLinesPerCategory[b.key] = b.sparkline === undefined ? {} : b.sparkline.buckets.reduce((acc2, cur2) => {
      acc2[cur2.key] = cur2.doc_count;
      return acc2;
    }, {});
    return {
      key: b.key,
      count: b.doc_count,
      examples: b.hit.hits.hits.map(h => (0, _lodash.get)(h._source, field))
    };
  });
  return {
    categories,
    sparkLinesPerCategory
  };
}