/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * 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 General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {QueryDslBoolQuery} from '@elastic/elasticsearch/lib/api/types.js';
import {SCSearchBooleanFilter} from '@openstapps/core';
import {QueryDslSpecificQueryContainer} from '../../types/util.js';
import {buildFilter} from '../filter.js';

/**
 * Converts a boolean filter to elasticsearch syntax
 * @param filter A search filter for the retrieval of the data
 */
export function buildBooleanFilter(filter: SCSearchBooleanFilter): QueryDslSpecificQueryContainer<'bool'> {
  const result: QueryDslBoolQuery = {
    minimum_should_match: 0,
    must: [],
    must_not: [],
    should: [],
  };

  if (filter.arguments.operation === 'and') {
    result.must = filter.arguments.filters.map(it => buildFilter(it));
  }

  if (filter.arguments.operation === 'or') {
    result.should = filter.arguments.filters.map(it => buildFilter(it));
    result.minimum_should_match = 1;
  }

  if (filter.arguments.operation === 'not') {
    result.must_not = filter.arguments.filters.map(it => buildFilter(it));
  }

  return {
    bool: result,
  };
}
