import { CustomFieldDef, CustomFieldValue } from "@open-mercato/core/modules/entities/data/entities";
const valueColumnForKind = (kind) => {
  switch (kind) {
    case "integer":
      return "valueInt";
    case "float":
      return "valueFloat";
    case "boolean":
      return "valueBool";
    case "multiline":
      return "valueMultiline";
    default:
      return "valueText";
  }
};
const expectedValuesFor = (condition) => {
  if (condition && typeof condition === "object" && !Array.isArray(condition)) {
    const maybeIn = condition.$in;
    if (Array.isArray(maybeIn)) return maybeIn;
  }
  return [condition];
};
const intersect = (current, next) => {
  if (current === null) return next;
  const result = /* @__PURE__ */ new Set();
  for (const id of next) {
    if (current.has(id)) result.add(id);
  }
  return result;
};
async function resolveRecordIdsForCustomFieldFilters(opts) {
  const { em, entityId, tenantId, filters } = opts;
  if (!filters.length) return /* @__PURE__ */ new Set();
  const keys = Array.from(new Set(filters.map(([key]) => key)));
  const tenantScope = tenantId ? { tenantId: { $in: [tenantId, null] } } : { tenantId: null };
  const defs = await em.find(CustomFieldDef, {
    entityId: String(entityId),
    key: { $in: keys },
    isActive: true,
    deletedAt: null,
    ...tenantScope
  });
  const kindByKey = /* @__PURE__ */ new Map();
  for (const def of defs) {
    if (!kindByKey.has(def.key)) kindByKey.set(def.key, def.kind);
  }
  let matched = null;
  for (const [key, condition] of filters) {
    const column = valueColumnForKind(kindByKey.get(key));
    const expectedValues = expectedValuesFor(condition).filter((value) => value !== void 0 && value !== null);
    if (!expectedValues.length) return /* @__PURE__ */ new Set();
    const rows = await em.find(
      CustomFieldValue,
      {
        entityId: String(entityId),
        fieldKey: key,
        deletedAt: null,
        [column]: { $in: expectedValues },
        ...tenantScope
      },
      { fields: ["recordId"] }
    );
    const ids = new Set(rows.map((row) => String(row.recordId)));
    matched = intersect(matched, ids);
    if (matched.size === 0) return matched;
  }
  return matched ?? /* @__PURE__ */ new Set();
}
export {
  resolveRecordIdsForCustomFieldFilters
};
//# sourceMappingURL=tenant-cf-filter.js.map
