import { loadCustomFieldValues } from "@open-mercato/shared/lib/crud/custom-fields";
async function loadCustomFieldSnapshot(em, { entityId, recordId, tenantId, organizationId, tenantFallbacks }) {
  const tenant = tenantId ?? null;
  const organization = organizationId ?? void 0;
  const records = await loadCustomFieldValues({
    em,
    entityId,
    recordIds: [recordId],
    tenantIdByRecord: { [recordId]: tenant },
    organizationIdByRecord: organization === void 0 ? void 0 : { [recordId]: organization ?? null },
    tenantFallbacks: tenantFallbacks ?? [tenant]
  });
  const raw = records[recordId] ?? {};
  const custom = {};
  for (const [key, value] of Object.entries(raw)) {
    if (key.startsWith("cf_")) custom[key.slice(3)] = value;
  }
  return custom;
}
function buildCustomFieldResetMap(before, after) {
  const values = {};
  const keys = /* @__PURE__ */ new Set();
  if (before) for (const key of Object.keys(before)) keys.add(key);
  if (after) for (const key of Object.keys(after)) keys.add(key);
  for (const key of keys) {
    const hasBefore = Boolean(before && Object.prototype.hasOwnProperty.call(before, key));
    if (hasBefore) {
      const beforeValue = before?.[key];
      if (beforeValue === null && Array.isArray(after?.[key])) {
        values[key] = [];
      } else {
        values[key] = beforeValue;
      }
    } else {
      values[key] = Array.isArray(after?.[key]) ? [] : null;
    }
  }
  return values;
}
function diffCustomFieldChanges(before, after) {
  const out = {};
  const keys = /* @__PURE__ */ new Set();
  if (before) for (const key of Object.keys(before)) keys.add(key);
  if (after) for (const key of Object.keys(after)) keys.add(key);
  for (const key of keys) {
    const prev = before ? before[key] : void 0;
    const next = after ? after[key] : void 0;
    if (!customFieldValuesEqual(prev, next)) {
      out[key] = { from: prev ?? null, to: next ?? null };
    }
  }
  return out;
}
function customFieldValuesEqual(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    return a.every((value, idx) => customFieldValuesEqual(value, b[idx]));
  }
  return a === b;
}
export {
  buildCustomFieldResetMap,
  diffCustomFieldChanges,
  loadCustomFieldSnapshot
};
//# sourceMappingURL=customFieldSnapshots.js.map
