import { HeaderType, type Filter, type Value } from '../types.ts';

export { default as SelectFilter } from './SelectFilter.tsx';
export { default as NumberFilter } from './NumberFilter.tsx';

const filterString = (value: string, data: string): boolean => {
  return data.toLowerCase().search(value.toLowerCase()) !== -1;
};
const filterNumber = (value: Value, data: any): boolean => {
  if (!Array.isArray(value)) {
    throw new Error(
      'Value should be an array in the form of [operator: string, value: number]',
    );
  }

  const [operator, numberValue] = value;

  if (numberValue === null) return true;

  switch (operator) {
    case '=':
      return data === numberValue;
    case '<':
      return data < numberValue;
    case '>':
      return data > numberValue;
    case '<=':
      return data <= numberValue;
    case '>=':
      return data >= numberValue;

    default:
      return data === numberValue;
  }
};
const filterSelect = (value: Value, data: any): boolean => {
  return data === value;
};
const filterMultiple = (value: Value, data: any): boolean => {
  if (value === null) {
    return true;
  }

  if (typeof value === 'string' || typeof value === 'number') {
    return data.includes(value);
  }

  return value.every((filter: string | number) => data.includes(filter));
};

export const resolveFilterByType = (filter: Filter, data: any): boolean => {
  switch (filter.type) {
    case HeaderType.String:
      return filterString(filter.value, data);
    case HeaderType.Number:
      return filterNumber(filter.value, data);
    case HeaderType.Select:
      return filterSelect(filter.value, data);
    case HeaderType.Multiple:
      return filterMultiple(filter.value, data);
  }

  return true;
};
