import { compact, isArray } from 'lodash';
interface FilterProps {
  key: string;
  rawValue: any;
  format?: string | ((val: any) => any);
  params: Record<string, any>;
}
export const FILTER_STRATEGIES = {
  range: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    if (rawValue === null) {
      params.byEqualCol[key] = null;
      params.byBetweenCol[key] = null;
    } else if (typeof rawValue === 'object' && (('min' in rawValue && 'max' in rawValue) || ('from' in rawValue && 'to' in rawValue) || ('start' in rawValue && 'end' in rawValue))) {
      params.byBetweenCol[key] = {
        from: getParamValue(rawValue.min ?? rawValue.from ?? rawValue.start, format),
        to: getParamValue(rawValue.max ?? rawValue.to ?? rawValue.end, format),
      };
    } else {
      params.byEqualCol[key] = getParamValue(rawValue, format);
    }
  },
  greater: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    params.byGreaterCol[key] = getParamValue(rawValue, format);
  },
  less: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    params.byLessCol[key] = getParamValue(rawValue, format);
  },
  custom: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    params.custom[key] = getParamValue(rawValue, format);
  },
  strict: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    params.byEqualCol[key] = getParamValue(rawValue, format);
  },
  default: (filterProps: FilterProps) => {
    const { key, rawValue, format, params } = filterProps;
    params.bycol[key] = getParamValue(rawValue, format);
  },
};

function getParamValue(rawValue: any, format?: string | ((val: any) => any)) {
  let formatFn: (val: any) => any;
  if (!format) {
    formatFn = (v: any) => v;
  } else {
    formatFn = typeof format === 'string' ? (v: object) => v[format] : format;
  }
  if (isArray(rawValue)) return compact(rawValue.map(formatFn));
  return formatFn(rawValue);
}
