import { CustomEntity } from "../data/entities.js";
async function upsertCustomEntity(em, entityId, opts) {
  const where = { entityId, organizationId: opts.organizationId ?? null, tenantId: opts.tenantId ?? null };
  const desired = {
    label: opts.label,
    description: opts.description ?? null,
    isActive: opts.isActive ?? true,
    showInSidebar: !!opts.showInSidebar,
    labelField: opts.labelField ?? null,
    defaultEditor: opts.defaultEditor ?? null
  };
  const dryRun = opts.dryRun === true;
  const createOnly = opts.createOnly === true;
  const apply = (ent) => {
    ent.label = desired.label;
    ent.description = desired.description;
    ent.isActive = desired.isActive;
    ent.showInSidebar = desired.showInSidebar;
    ent.labelField = desired.labelField;
    ent.defaultEditor = desired.defaultEditor;
    ent.updatedAt = /* @__PURE__ */ new Date();
    if (ent.deletedAt) ent.deletedAt = null;
  };
  const isDifferent = (ent) => {
    if (ent.label !== desired.label) return true;
    if ((ent.description ?? null) !== desired.description) return true;
    if ((ent.isActive ?? true) !== desired.isActive) return true;
    if ((ent.showInSidebar ?? false) !== desired.showInSidebar) return true;
    if ((ent.labelField ?? null) !== desired.labelField) return true;
    if ((ent.defaultEditor ?? null) !== desired.defaultEditor) return true;
    if (ent.deletedAt != null) return true;
    return false;
  };
  return em.transactional(async (tem) => {
    const now = /* @__PURE__ */ new Date();
    try {
      let ent = await tem.findOne(CustomEntity, where);
      if (!ent) {
        if (dryRun) return "created";
        ent = tem.create(CustomEntity, { ...where, ...desired, createdAt: now, updatedAt: now, deletedAt: null });
        await tem.persist(ent).flush();
        return "created";
      }
      if (createOnly) return "unchanged";
      if (!isDifferent(ent)) return "unchanged";
      if (dryRun) return "updated";
      apply(ent);
      await tem.flush();
      return "updated";
    } catch (error) {
      if (error?.code === "23505" || error?.message?.includes("duplicate key")) {
        const ent = await tem.findOne(CustomEntity, where);
        if (!ent) throw error;
        if (createOnly) return "unchanged";
        if (!isDifferent(ent)) return "unchanged";
        if (dryRun) return "updated";
        apply(ent);
        await tem.flush();
        return "updated";
      }
      throw error;
    }
  });
}
export {
  upsertCustomEntity
};
//# sourceMappingURL=register.js.map
