/*
 * Copyright (C) 2019 StApps
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
import {
  AggregateName,
  AggregationsAggregate,
  AggregationsFiltersAggregate,
  AggregationsMultiTermsBucket,
} from '@elastic/elasticsearch/lib/api/types.js';
import {SCFacet, SCThingType} from '@openstapps/core';

/**
 * Parses elasticsearch aggregations (response from es) to facets for the app
 * @param aggregationResponse - aggregations response from elasticsearch
 */
export function parseAggregations(
  aggregationResponse: Record<AggregateName, AggregationsAggregate>,
): SCFacet[] {
  const facets: SCFacet[] = [];

  for (const aggregateName in aggregationResponse) {
    const aggregation = aggregationResponse[aggregateName] as AggregationsMultiTermsBucket;
    const type = aggregateName === '@all' ? {} : {onlyOnType: aggregateName as SCThingType};

    for (const field in aggregation) {
      const fieldAggregate = aggregation[field] as AggregationsFiltersAggregate;
      if (typeof fieldAggregate !== 'object') continue;

      const buckets = Object.values(fieldAggregate.buckets).map(bucket => {
        return {
          count: bucket.doc_count,
          key: bucket.key as string,
        };
      });
      if (buckets.length === 0) continue;

      facets.push({
        buckets,
        field,
        ...type,
      });
    }
  }

  return facets;
}
