/*
 * 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 {QueryDslFunctionScoreContainer} from '@elastic/elasticsearch/lib/api/types.js';
import {SCBackendConfigurationSearchBoostingType} from '@openstapps/core';
import {QueryDslSpecificQueryContainer} from '../../types/util.js';

/**
 * Creates boost functions for all type boost configurations
 * @param boostingTypes Array of type boosting configurations
 */
export function buildFunctionsForBoostingTypes(
  boostingTypes: SCBackendConfigurationSearchBoostingType[],
): QueryDslFunctionScoreContainer[] {
  const functions: QueryDslFunctionScoreContainer[] = [];

  for (const boostingForOneSCType of boostingTypes) {
    const typeFilter: QueryDslSpecificQueryContainer<'term'> = {
      term: {
        type: boostingForOneSCType.type,
      },
    };

    functions.push({
      filter: typeFilter,
      weight: boostingForOneSCType.factor,
    });

    if (boostingForOneSCType.fields !== undefined) {
      const fields = boostingForOneSCType.fields;

      for (const fieldName in boostingForOneSCType.fields) {
        if (boostingForOneSCType.fields.hasOwnProperty(fieldName)) {
          const boostingForOneField = fields[fieldName];

          for (const value in boostingForOneField) {
            if (boostingForOneField.hasOwnProperty(value)) {
              const factor = boostingForOneField[value];

              // build term filter
              const termFilter: QueryDslSpecificQueryContainer<'term'> = {
                term: {},
              };
              termFilter.term[`${fieldName}.raw`] = value;

              functions.push({
                filter: {
                  bool: {
                    must: [typeFilter, termFilter],
                    should: [],
                  },
                },
                weight: factor,
              });
            }
          }
        }
      }
    }
  }

  return functions;
}
