import { useMemo } from "react";
import { useEnvironment, QueryLanguage } from "@contember/binding";
const useDesugaredOptionPath = (props, filter) => {
  const environment = useEnvironment();
  const isEntityList = "optionsStaticRender" in props || "optionLabel" in props;
  const lazy = props.lazy;
  return useMemo(() => {
    if (isEntityList) {
      return getDesugaredEntityList(props.options, environment, lazy, filter);
    }
    return getDesugaredFieldList(props.options, environment, lazy, filter);
  }, [environment, filter, isEntityList, lazy, props.options]);
};
const getDesugaredEntityList = (options, environment, lazyOptions, filter) => {
  const sugaredList = typeof options === "string" || !("entities" in options) ? { entities: options } : options;
  const qualifiedEntityList = QueryLanguage.desugarQualifiedEntityList(sugaredList, environment);
  return {
    ...qualifiedEntityList,
    filter: filter && qualifiedEntityList.filter ? { and: [filter, qualifiedEntityList.filter] } : qualifiedEntityList.filter ?? filter,
    limit: getLazyLimit(lazyOptions, filter === void 0) ?? qualifiedEntityList.limit
  };
};
const getDesugaredFieldList = (options, environment, lazyOptions, filter) => {
  const sugaredList = typeof options === "string" || !("fields" in options) ? { fields: options } : options;
  const desugarQualifiedFieldList = QueryLanguage.desugarQualifiedFieldList(sugaredList, environment);
  return {
    ...desugarQualifiedFieldList,
    filter: filter && desugarQualifiedFieldList.filter ? { and: [filter, desugarQualifiedFieldList.filter] } : desugarQualifiedFieldList.filter ?? filter,
    limit: getLazyLimit(lazyOptions, filter === void 0) ?? desugarQualifiedFieldList.limit
  };
};
const DEFAULT_LAZY_LIMIT = 100;
const DEFAULT_LAZY_INIT_LIMIT = 20;
const getLazyLimit = (lazyOptions, isInitial) => {
  if (!lazyOptions) {
    return void 0;
  }
  const normalized = typeof lazyOptions === "object" ? lazyOptions : {};
  if (isInitial) {
    return normalized.initialLimit ?? Math.min(normalized.limit ?? DEFAULT_LAZY_INIT_LIMIT, DEFAULT_LAZY_INIT_LIMIT);
  }
  return normalized.limit ?? DEFAULT_LAZY_LIMIT;
};
export { getDesugaredEntityList, getDesugaredFieldList, getLazyLimit, useDesugaredOptionPath };
//# sourceMappingURL=useDesugaredOptionPath.js.map
