import { QuerySettings } from '../../types';
import { Filter } from '../schemas';
import { filterGroupMapping } from './filter-group.mapping';
import { filterInputMapping } from './filter-input.mapping';
import { orderByOptionMapping } from './order-by-option.mapping';

/**
 * Maps a QuerySettings object to a Filter object
 *
 * This is the main mapping function that transforms query settings into a
 * complete Filter object structure. It:
 * 1. Creates filter groups from both filter and input settings
 * 2. Maps all inputs from each group to their corresponding filter inputs
 * 3. Maps order by options if present
 *
 * The resulting Filter object can be used by filter components to render
 * the appropriate UI and handle user interactions.
 *
 * @param settings - The source query settings to map
 * @returns A fully populated Filter object with groups, inputs, and ordering options
 */
export function filterMapping(settings: QuerySettings): Filter {
  const filter: Filter = {
    groups: [],
    inputs: [],
    orderBy: [],
  };

  const groups = [...(settings.filter || []), ...(settings.input || [])];

  for (const group of groups) {
    filter.groups.push(filterGroupMapping(group));

    if (Array.isArray(group.input)) {
      for (const input of group.input) {
        const inputs = filterInputMapping(group.group, input);
        if (inputs === undefined) {
          continue;
        }
        filter.inputs.push(inputs);
      }
    }
  }

  if (settings.orderBy) {
    for (const orderBy of settings.orderBy) {
      filter.orderBy.push(orderByOptionMapping(orderBy));
    }
  }

  return filter;
}
