import { CustomFieldDef } from "../data/entities.js";
const CONFIG_PASSTHROUGH_KEYS = [
  "label",
  "description",
  "fieldset",
  "fieldsets",
  "group",
  "options",
  "optionsUrl",
  "defaultValue",
  "required",
  "multi",
  "filterable",
  "formEditable",
  "listVisible",
  "indexed",
  "editor",
  "input",
  "relatedEntityId",
  "dictionaryId",
  "dictionaryInlineCreate",
  "validation",
  "maxAttachmentSizeMb",
  "acceptExtensions",
  "sourceMetadata"
];
function normalizeValue(value) {
  if (Array.isArray(value)) return value.map((item) => normalizeValue(item));
  if (value && typeof value === "object") {
    return Object.keys(value).sort((a, b) => a.localeCompare(b)).reduce((acc, key) => {
      acc[key] = normalizeValue(value[key]);
      return acc;
    }, {});
  }
  return value;
}
function configEquals(a, b) {
  return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null));
}
async function ensureCustomFieldDefinitions(em, sets, scope) {
  let created = 0;
  let updated = 0;
  let unchanged = 0;
  const entityIds = Array.from(new Set(sets.map((set) => set.entity)));
  const fieldKeys = Array.from(new Set(sets.flatMap((set) => set.fields.map((field) => field.key))));
  const existingByKey = /* @__PURE__ */ new Map();
  if (entityIds.length > 0 && fieldKeys.length > 0) {
    const existingDefs = await em.find(CustomFieldDef, {
      entityId: { $in: entityIds },
      organizationId: scope.organizationId,
      tenantId: scope.tenantId,
      key: { $in: fieldKeys }
    });
    for (const def of existingDefs) {
      existingByKey.set(`${def.entityId}|${def.key}`, def);
    }
  }
  let dirty = false;
  for (const set of sets) {
    for (const field of set.fields) {
      const existing = existingByKey.get(`${set.entity}|${field.key}`) ?? null;
      const configJson = {};
      for (const key of CONFIG_PASSTHROUGH_KEYS) {
        const value = field[key];
        if (value !== void 0) configJson[key] = value;
      }
      if (!existing) {
        if (!scope.dryRun) {
          const createdDef = em.create(CustomFieldDef, {
            entityId: set.entity,
            organizationId: scope.organizationId,
            tenantId: scope.tenantId,
            key: field.key,
            kind: field.kind,
            configJson,
            isActive: true,
            createdAt: /* @__PURE__ */ new Date(),
            updatedAt: /* @__PURE__ */ new Date()
          });
          em.persist(createdDef);
          existingByKey.set(`${set.entity}|${field.key}`, createdDef);
          dirty = true;
        }
        created++;
        continue;
      }
      const kindChanged = existing.kind !== field.kind;
      const configChanged = !configEquals(existing.configJson ?? null, configJson);
      const needsActivation = existing.isActive !== true || existing.deletedAt != null;
      if (scope.createOnly) {
        unchanged++;
        continue;
      }
      if (!kindChanged && !configChanged && !needsActivation) {
        unchanged++;
        continue;
      }
      if (!scope.dryRun) {
        existing.kind = field.kind;
        existing.configJson = configJson;
        existing.isActive = true;
        existing.updatedAt = /* @__PURE__ */ new Date();
        if (existing.deletedAt) existing.deletedAt = null;
        em.persist(existing);
        dirty = true;
      }
      updated++;
    }
  }
  if (dirty) {
    await em.flush();
  }
  return { created, updated, unchanged };
}
export {
  ensureCustomFieldDefinitions
};
//# sourceMappingURL=field-definitions.js.map
