import { useCallback } from "react";
import { useSearchFields } from "./useSearchFields.js";
import { BindingError, wrapFilterInHasOnes } from "@contember/binding";
const useCreateOptionsFilter = (desugaredOptionPath, searchByFields, lazy) => {
  const desugaredSearchFields = useSearchFields(searchByFields);
  const lazyFilter = lazy && typeof lazy === "object" && lazy.createFilter;
  if (lazy && desugaredSearchFields.length === 0 && !lazyFilter && !("field" in desugaredOptionPath)) {
    throw new BindingError(`Lazy select has no fields specified for a search. Please set either lazy.createFilter or searchByFields option.`);
  }
  return useCallback((input) => {
    if (lazyFilter) {
      return lazyFilter(input);
    }
    if (!input) {
      return void 0;
    }
    if (desugaredSearchFields.length) {
      const or = [];
      for (const field of desugaredSearchFields) {
        or.push(wrapFilterInHasOnes(field.hasOneRelationPath, {
          [field.field]: { containsCI: input }
        }));
      }
      return { or };
    }
    if ("field" in desugaredOptionPath) {
      return wrapFilterInHasOnes(desugaredOptionPath.hasOneRelationPath, {
        [desugaredOptionPath.field]: { containsCI: input }
      });
    }
    {
      throw new BindingError(`Lazy select has no fields specified for a search. Please set either lazy.createFilter or searchByFields option.`);
    }
  }, [desugaredOptionPath, desugaredSearchFields, lazyFilter]);
};
export { useCreateOptionsFilter };
//# sourceMappingURL=useCreateOptionsFilter.js.map
