import { warnOnCiphertextLikeFallback } from "../query/ciphertext-search-warning.js";
import { resolveTenantEncryptionService } from "./customFieldValues.js";
import { resolveEntityIdFromMetadata } from "./entityIds.js";
const LIKE_OPERATORS = /* @__PURE__ */ new Set(["$like", "$ilike", "$re", "$fulltext"]);
const LOGICAL_OPERATORS = /* @__PURE__ */ new Set(["$and", "$or", "$not", "$every", "$some", "$none"]);
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
const isOperatorObject = (value) => {
  if (!isPlainObject(value)) return false;
  const keys = Object.keys(value);
  return keys.length > 0 && keys.every((key) => key.startsWith("$"));
};
function walkFilter(node, field, out) {
  if (Array.isArray(node)) {
    for (const item of node) walkFilter(item, field, out);
    return;
  }
  if (!isPlainObject(node)) return;
  for (const [key, value] of Object.entries(node)) {
    if (LIKE_OPERATORS.has(key)) {
      if (field) out.add(field);
      continue;
    }
    if (LOGICAL_OPERATORS.has(key)) {
      walkFilter(value, field, out);
      continue;
    }
    if (key.startsWith("$")) continue;
    if (isOperatorObject(value)) walkFilter(value, key, out);
  }
}
function collectLikeFilterFields(where) {
  const found = /* @__PURE__ */ new Set();
  walkFilter(where, null, found);
  return Array.from(found);
}
const isWarningEnabled = () => process.env.NODE_ENV !== "production";
function resolveEntityId(em, entityName) {
  const metadata = em?.getMetadata?.();
  if (!metadata || typeof metadata.find !== "function") return null;
  const name = typeof entityName === "string" ? entityName : entityName?.name;
  if (!name) return null;
  return resolveEntityIdFromMetadata(metadata.find(name) ?? void 0);
}
async function warnOnEncryptedLikeFilter(params) {
  if (!isWarningEnabled()) return;
  const fields = collectLikeFilterFields(params.where);
  if (!fields.length) return;
  try {
    const entity = resolveEntityId(params.em, params.entityName);
    if (!entity) return;
    const service = params.encryptionService ?? resolveTenantEncryptionService(params.em);
    await warnOnCiphertextLikeFallback({
      entity,
      fields,
      tenantId: params.tenantId ?? null,
      reason: "raw-orm-filter",
      service
    });
  } catch {
  }
}
export {
  collectLikeFilterFields,
  warnOnEncryptedLikeFilter
};
//# sourceMappingURL=likeFilterWarning.js.map
