import { FilterOperator, OperatorFilterValue } from '@wix/bex-core';

/**
 * Transform an operator filter value to WQL (Wix Query Language) format
 * @param filterName - The name of the field being filtered
 * @param filterValue - The operator filter value containing operator and value
 * @returns Array of WQL filter objects, or empty array if filter should not be applied
 */
export const transformOperatorFilterToWQL = <T,>(
  filterName: string,
  filterValue: OperatorFilterValue<T>,
) => {
  if (!filterValue) {
    return [];
  }

  const { operator, value } = filterValue;

  if (operator === FilterOperator.IS_EMPTY) {
    return [
      {
        [filterName]: {
          $eq: null,
        },
      },
    ];
  }

  if (operator === FilterOperator.EXISTS) {
    return [
      {
        [filterName]: {
          $exists: true,
        },
      },
    ];
  }

  if (value === null || value === undefined || value === '') {
    return [];
  }

  switch (operator) {
    case FilterOperator.EQUALS:
      return [
        {
          [filterName]: {
            $eq: value,
          },
        },
      ];

    case FilterOperator.NOT_EQUALS:
      return [
        {
          $not: {
            [filterName]: {
              $eq: value,
            },
          },
        },
      ];

    case FilterOperator.IN:
      return [
        {
          [filterName]: {
            $in: Array.isArray(value) ? value : [value],
          },
        },
      ];

    case FilterOperator.NOT_IN:
      return [
        {
          [filterName]: {
            $nin: Array.isArray(value) ? value : [value],
          },
        },
      ];

    case FilterOperator.STARTS_WITH:
      return [
        {
          [filterName]: {
            $startsWith: value,
          },
        },
      ];

    case FilterOperator.CONTAINS:
      return [
        {
          [filterName]: {
            $contains: value,
          },
        },
      ];

    case FilterOperator.NOT_CONTAINS:
      return [
        {
          $not: {
            [filterName]: {
              $contains: value,
            },
          },
        },
      ];

    case FilterOperator.LESS_THAN:
      return [
        {
          [filterName]: {
            $lt: value,
          },
        },
      ];

    case FilterOperator.LESS_THAN_OR_EQUAL:
      return [
        {
          [filterName]: {
            $lte: value,
          },
        },
      ];

    case FilterOperator.GREATER_THAN:
      return [
        {
          [filterName]: {
            $gt: value,
          },
        },
      ];

    case FilterOperator.GREATER_THAN_OR_EQUAL:
      return [
        {
          [filterName]: {
            $gte: value,
          },
        },
      ];

    default:
      return [];
  }
};
