import {
  deserializeAdvancedFilter,
  deserializeTree,
  flatToTree,
  convertAdvancedFilterToWhere
} from "../query/advanced-filter.js";
import { compileTreeToWhere } from "../query/advanced-filter-tree.js";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "crud" });
function splitOrClauses(filters) {
  const directFilters = {};
  let orClauses = null;
  for (const [key, value] of Object.entries(filters)) {
    if (key === "$or" && Array.isArray(value)) {
      orClauses = value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
      continue;
    }
    directFilters[key] = value;
  }
  return { directFilters, orClauses };
}
function mergeAdvancedFilters(existingFilters, query) {
  const advancedState = deserializeAdvancedFilter(query);
  if (!advancedState) return existingFilters;
  const advancedWhere = convertAdvancedFilterToWhere(advancedState);
  if (!Object.keys(advancedWhere).length) return existingFilters;
  if ("$or" in advancedWhere) {
    if (!Object.keys(existingFilters).length) return advancedWhere;
    const { directFilters: existingDirect, orClauses: existingOrClauses } = splitOrClauses(existingFilters);
    const advancedClauses = Array.isArray(advancedWhere.$or) ? advancedWhere.$or.filter(
      (entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry)
    ) : [];
    if (!advancedClauses.length) return existingFilters;
    if (!existingOrClauses?.length) {
      return {
        ...existingDirect,
        $or: advancedClauses
      };
    }
    const combinedClauses = [];
    for (const leftClause of existingOrClauses) {
      for (const rightClause of advancedClauses) {
        combinedClauses.push({
          ...leftClause,
          ...rightClause
        });
      }
    }
    return combinedClauses.length ? {
      ...existingDirect,
      $or: combinedClauses
    } : existingFilters;
  }
  return { ...existingFilters, ...advancedWhere };
}
function mergeAdvancedFilterTree(routeFilters, tree) {
  if (!tree) return routeFilters;
  const treeWhere = compileTreeToWhere(tree);
  if (!treeWhere) return routeFilters;
  if (Object.keys(routeFilters).length === 0) return treeWhere;
  return { $and: [routeFilters, treeWhere] };
}
function mergeAdvancedFiltersFromQuery(routeFilters, query) {
  const v2 = deserializeTree(query);
  if (v2) return mergeAdvancedFilterTree(routeFilters, v2);
  const flat = deserializeAdvancedFilter(query);
  if (!flat) return routeFilters;
  return mergeAdvancedFilterTree(routeFilters, flatToTree(flat));
}
function consumeAdvancedFilterState(query) {
  let tree = deserializeTree(query);
  if (!tree) {
    const flat = deserializeAdvancedFilter(query);
    if (flat) {
      tree = flatToTree(flat);
      if (process.env.NODE_ENV !== "production") {
        const sentinel = "__OM_FILTER_V1_WARNED";
        const g = globalThis;
        if (!g[sentinel]) {
          g[sentinel] = true;
          logger.warn("Legacy v1 advanced-filter URL detected; auto-upgraded to v2 tree");
        }
      }
    }
  }
  for (const key of Object.keys(query)) {
    if (key.startsWith("filter[")) {
      delete query[key];
    }
  }
  return tree;
}
export {
  consumeAdvancedFilterState,
  mergeAdvancedFilterTree,
  mergeAdvancedFilters,
  mergeAdvancedFiltersFromQuery
};
//# sourceMappingURL=advanced-filter-integration.js.map
