import {
  CustomField,
  CustomFieldType,
  ExtractFilterValue,
  FiltersMap,
  RawFilters,
} from '@wix/bex-core';
import { ToolbarCollectionState } from '../../state';
import { transformCustomDateFilterToWQL } from './transformCustomDateFilterToWQL';
import { transformCustomCheckboxToWQL } from './transformCustomCheckboxToWQL';
import { transformCustomNumberRangeFilterToWQL } from './transformCustomNumberRangeFilterToWQL';
import { prefixFieldWithNamespace } from '../../state/simplifyExtendedColumns';
import { transformOperatorFilterToWQL } from './transformOperatorFilterToWQL';

export const transformCustomFiltersToWQL = <F extends FiltersMap>(
  state: { toolbar: ToolbarCollectionState<any, F> },
  filters: RawFilters<F>,
) => {
  const transformToWqlMapper: {
    [key in CustomFieldType]?: (
      filterName: string,
      filterValue: { [P in keyof F]: ExtractFilterValue<F[P]> }[string],
    ) => any[];
  } = {
    date: transformCustomDateFilterToWQL,
    dateTime: transformCustomDateFilterToWQL,
    checkbox: transformCustomCheckboxToWQL,
    decimal: transformCustomNumberRangeFilterToWQL,
    integer: transformCustomNumberRangeFilterToWQL,
    shortText: transformOperatorFilterToWQL,
    longText: transformOperatorFilterToWQL,
    url: transformOperatorFilterToWQL,
  };

  const platformizedFilters = Object.keys(filters).reduce(
    (acc: any[], filterId) => {
      const filterValue = filters[filterId];
      const currCustomField =
        state.toolbar.collectionDataExtension?.dataExtension.filterableCustomFields.find(
          (field: CustomField) => field.id === filterId,
        );

      if (!currCustomField || filterValue == null) {
        return acc;
      }

      const filterName = prefixFieldWithNamespace(
        currCustomField.id,
        currCustomField.namespace,
      );

      const transformToWql = transformToWqlMapper[currCustomField.type];
      if (!transformToWql) {
        return acc;
      }

      acc.push(...transformToWql(filterName, filterValue));

      return acc;
    },
    [],
  );

  return { $and: platformizedFilters };
};
