"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import React, { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { invalidateCustomFieldDefs } from "@open-mercato/ui/backend/utils/customFieldDefs";
import { upsertCustomEntitySchema, upsertCustomFieldDefSchema } from "@open-mercato/core/modules/entities/data/validators";
import { z } from "zod";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import Link from "next/link";
import { Button } from "@open-mercato/ui/primitives/button";
import { loadGeneratedFieldRegistrations } from "@open-mercato/ui/backend/fields/registry";
import { createCrudFormError, raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { FieldDefinitionsEditor } from "@open-mercato/ui/backend/custom-fields/FieldDefinitionsEditor";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { normalizeCustomFieldOptions } from "@open-mercato/shared/modules/entities/options";
import { TranslationManager } from "@open-mercato/core/modules/translations/components/TranslationManager";
function readVersionToken(value) {
  return typeof value === "string" && value.length > 0 ? value : null;
}
function EditDefinitionsPage({ params }) {
  React.useEffect(() => {
    loadGeneratedFieldRegistrations().catch(() => {
    });
  }, []);
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useT();
  const queryClient = useQueryClient();
  const entityId = useMemo(() => decodeURIComponent(params?.entityId || ""), [params]);
  const [label, setLabel] = useState("");
  const [entitySource, setEntitySource] = useState("custom");
  const [entityFormLoading, setEntityFormLoading] = useState(true);
  const [entityInitial, setEntityInitial] = useState({});
  const [defs, setDefs] = useState([]);
  const [defsVersion, setDefsVersion] = useState(null);
  const [orderDirty, setOrderDirty] = useState(false);
  const [orderSaving, setOrderSaving] = useState(false);
  const listRef = React.useRef(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [deletedKeys, setDeletedKeys] = useState([]);
  const [defErrors, setDefErrors] = useState({});
  const [fieldsets, setFieldsets] = useState([]);
  const [activeFieldset, setActiveFieldset] = useState(null);
  const [singleFieldsetPerRecord, setSingleFieldsetPerRecord] = useState(true);
  const [translateDef, setTranslateDef] = useState(null);
  const translateFields = React.useMemo(() => {
    if (!translateDef) return void 0;
    const { def } = translateDef;
    const fields2 = ["label", "description"];
    const options = normalizeCustomFieldOptions(def.configJson?.options);
    for (const opt of options) {
      if (opt.value) fields2.push(`options.${opt.value}.label`);
    }
    return fields2;
  }, [translateDef]);
  const translateBaseValues = React.useMemo(() => {
    if (!translateDef) return void 0;
    const { def } = translateDef;
    const base = {};
    if (typeof def.configJson?.label === "string") base.label = def.configJson.label;
    if (typeof def.configJson?.description === "string") base.description = def.configJson.description;
    const options = normalizeCustomFieldOptions(def.configJson?.options);
    for (const opt of options) {
      if (opt.value && opt.label) base[`options.${opt.value}.label`] = opt.label;
    }
    return base;
  }, [translateDef]);
  const requestedFieldset = React.useMemo(() => {
    const raw = searchParams?.get("fieldset");
    return raw && raw.trim().length ? raw.trim() : null;
  }, [searchParams]);
  const embedFieldsetView = React.useMemo(() => searchParams?.get("view") === "fieldset", [searchParams]);
  const normalizeGroupPayload = React.useCallback((value) => {
    if (!value) return null;
    if (typeof value === "string") {
      const code2 = value.trim();
      return code2 ? { code: code2 } : null;
    }
    if (typeof value !== "object") return null;
    const entry = value;
    const code = typeof entry.code === "string" ? entry.code.trim() : "";
    if (!code) return null;
    const group = { code };
    if (typeof entry.title === "string" && entry.title.trim()) group.title = entry.title.trim();
    if (typeof entry.hint === "string" && entry.hint.trim()) group.hint = entry.hint.trim();
    return group;
  }, []);
  const buildFieldsetPayload = React.useCallback(() => {
    const groupMap = /* @__PURE__ */ new Map();
    defs.forEach((definition) => {
      const code = typeof definition.configJson?.fieldset === "string" ? definition.configJson.fieldset : null;
      if (!code) return;
      const normalized = normalizeGroupPayload(definition.configJson?.group);
      if (!normalized) return;
      const list = groupMap.get(code) ?? [];
      if (!list.some((entry) => entry.code === normalized.code)) {
        list.push(normalized);
        groupMap.set(code, list);
      }
    });
    return fieldsets.map((fs) => ({
      ...fs,
      groups: groupMap.get(fs.code) ?? []
    }));
  }, [defs, fieldsets, normalizeGroupPayload]);
  const validateDef = React.useCallback((d) => {
    const parsed = upsertCustomFieldDefSchema.safeParse({ entityId, key: d.key, kind: d.kind, configJson: d.configJson, isActive: d.isActive });
    if (parsed.success) return {};
    const errs = {};
    for (const issue of parsed.error.issues) {
      if ((issue.path || []).includes("key")) errs.key = issue.message;
      if ((issue.path || []).includes("kind")) errs.kind = issue.message;
    }
    return errs;
  }, [entityId, requestedFieldset]);
  const validateAndSetErrorAt = (index, d) => {
    const errs = validateDef(d);
    setDefErrors((prev) => ({ ...prev, [index]: errs }));
    return !errs.key && !errs.kind;
  };
  const validateAll = () => {
    const nextErrors = {};
    defs.forEach((d, i) => {
      nextErrors[i] = validateDef(d);
    });
    setDefErrors(nextErrors);
    return Object.values(nextErrors).every((e) => !e.key && !e.kind);
  };
  useEffect(() => {
    let mounted = true;
    async function load() {
      setLoading(true);
      try {
        const entJson = await readApiResultOrThrow(
          "/api/entities/entities",
          void 0,
          { errorMessage: "Failed to load entity metadata", fallback: { items: [] } }
        );
        const ent = (entJson.items || []).find((x) => x.entityId === entityId);
        if (mounted) {
          const record = ent;
          const labelValue = typeof record?.label === "string" && record.label.trim().length > 0 ? record.label : entityId;
          const descriptionValue = typeof record?.description === "string" ? record.description : "";
          const labelFieldValue = typeof record?.labelField === "string" && record.labelField.length > 0 ? record.labelField : "name";
          const defaultEditorValue = typeof record?.defaultEditor === "string" ? record.defaultEditor : "";
          const showInSidebarValue = record?.showInSidebar === true;
          const updatedAtValue = typeof record?.updatedAt === "string" && record.updatedAt.length > 0 ? record.updatedAt : void 0;
          setLabel(labelValue);
          if (record?.source === "code" || record?.source === "custom") setEntitySource(record.source);
          setEntityInitial({
            label: labelValue,
            description: descriptionValue,
            labelField: labelFieldValue,
            defaultEditor: defaultEditorValue,
            showInSidebar: showInSidebarValue,
            updatedAt: updatedAtValue
          });
          setEntityFormLoading(false);
        }
        const json = await readApiResultOrThrow(
          `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,
          void 0,
          { errorMessage: "Failed to load entity definitions", fallback: { items: [], deletedKeys: [] } }
        );
        if (mounted) {
          const loaded = (json.items || []).map((d) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }));
          loaded.sort(
            (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)
          );
          setDefs(loaded);
          setDefsVersion(readVersionToken(json.version));
          setDefErrors({});
          setDeletedKeys(Array.isArray(json.deletedKeys) ? json.deletedKeys : []);
          const loadedFieldsets = Array.isArray(json.fieldsets) ? json.fieldsets : [];
          setFieldsets(loadedFieldsets);
          setActiveFieldset((prev) => {
            if (requestedFieldset && loadedFieldsets.some((fs) => fs.code === requestedFieldset)) {
              return requestedFieldset;
            }
            if (prev && loadedFieldsets.some((fs) => fs.code === prev)) return prev;
            return loadedFieldsets[0]?.code ?? null;
          });
          setSingleFieldsetPerRecord(json.settings?.singleFieldsetPerRecord !== false);
        }
      } catch (e) {
        if (mounted) setError(e.message || "Failed to load");
      } finally {
        if (mounted) setLoading(false);
      }
    }
    if (entityId) load();
    return () => {
      mounted = false;
    };
  }, [entityId]);
  function addField() {
    setDefs((arr) => [
      ...arr,
      {
        key: "",
        kind: "text",
        configJson: activeFieldset ? { fieldset: activeFieldset } : {},
        isActive: true
      }
    ]);
  }
  async function restoreField(key) {
    try {
      const call = await apiCall("/api/entities/definitions.restore", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ entityId, key })
      });
      if (!call.ok) {
        await raiseCrudError(call.response, "Failed to restore field");
      }
      const j2 = await readApiResultOrThrow(
        `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,
        void 0,
        { errorMessage: "Failed to reload field definitions", fallback: { items: [], deletedKeys: [] } }
      );
      const loaded = (j2.items || []).map((d) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }));
      loaded.sort(
        (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)
      );
      setDefs(loaded);
      setDefsVersion(readVersionToken(j2.version));
      setDeletedKeys(Array.isArray(j2.deletedKeys) ? j2.deletedKeys : []);
      flash(`Restored ${key}`, "success");
      await invalidateCustomFieldDefs(queryClient, entityId);
    } catch (e) {
      flash(e?.message || "Failed to restore field", "error");
    }
  }
  async function saveAll() {
    setSaving(true);
    setError(null);
    try {
      if (!validateAll()) {
        flash("Please fix validation errors in field definitions", "error");
        throw new Error("Validation failed");
      }
      const payload = {
        entityId,
        definitions: defs.filter((d) => !!d.key).map((d) => ({
          key: d.key,
          kind: d.kind,
          configJson: d.configJson,
          isActive: d.isActive !== false
        }))
      };
      const call = await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(defsVersion),
        () => apiCall("/api/entities/definitions.batch", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(payload)
        })
      );
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
        await raiseCrudError(call.response, "Failed to save definitions");
      }
      setDefsVersion(readVersionToken(call.result?.version));
      await invalidateCustomFieldDefs(queryClient, entityId);
      router.push(`/backend/entities/user?flash=Definitions%20saved&type=success`);
    } catch (e) {
      setError(e.message || "Failed to save");
    } finally {
      setSaving(false);
    }
  }
  async function removeField(idx) {
    const def = defs[idx];
    if (!def) return;
    if (def.key) {
      try {
        const call = await apiCall("/api/entities/definitions", {
          method: "DELETE",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ entityId, key: def.key })
        });
        if (!call.ok) {
          await raiseCrudError(call.response, "Failed to delete field");
        }
        setDefsVersion(readVersionToken(call.result?.version));
      } catch (error2) {
        const message = error2 instanceof Error ? error2.message : "Failed to delete field";
        flash(message, "error");
        return;
      }
    }
    setDefs((arr) => arr.filter((_, i) => i !== idx));
    setOrderDirty(true);
    if (def.key) {
      await invalidateCustomFieldDefs(queryClient, entityId);
    }
  }
  const handleFieldsetCodeChange = React.useCallback((previousCode, nextCode) => {
    if (!previousCode || !nextCode || previousCode === nextCode) return;
    setDefs(
      (arr) => arr.map((entry) => {
        const current = typeof entry.configJson?.fieldset === "string" ? entry.configJson.fieldset : void 0;
        if (current !== previousCode) return entry;
        const nextConfig = { ...entry.configJson || {} };
        nextConfig.fieldset = nextCode;
        return { ...entry, configJson: nextConfig };
      })
    );
    setActiveFieldset((current) => current === previousCode ? nextCode : current);
  }, []);
  const handleFieldsetRemoved = React.useCallback((code) => {
    if (!code) return;
    setDefs(
      (arr) => arr.map((entry) => {
        const current = typeof entry.configJson?.fieldset === "string" ? entry.configJson.fieldset : void 0;
        if (current !== code) return entry;
        const nextConfig = { ...entry.configJson || {} };
        delete nextConfig.fieldset;
        delete nextConfig.group;
        return { ...entry, configJson: nextConfig };
      })
    );
  }, []);
  async function saveOrderIfDirty() {
    if (!orderDirty) return;
    setOrderSaving(true);
    try {
      if (!validateAll()) throw new Error("Validation failed");
      const payload = {
        entityId,
        definitions: defs.filter((d) => !!d.key).map((d) => ({
          key: d.key,
          kind: d.kind,
          configJson: d.configJson,
          isActive: d.isActive !== false
        }))
      };
      const call = await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(defsVersion),
        () => apiCall("/api/entities/definitions.batch", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(payload)
        })
      );
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) {
          setOrderDirty(false);
          return;
        }
        await raiseCrudError(call.response, "Failed to save order");
      }
      setDefsVersion(readVersionToken(call.result?.version));
      setOrderDirty(false);
      flash("Order saved", "success");
      await invalidateCustomFieldDefs(queryClient, entityId);
    } catch (e) {
      flash(e?.message || "Failed to save order", "error");
    } finally {
      setOrderSaving(false);
    }
  }
  const entityFormSchema = upsertCustomEntitySchema.pick({ label: true, description: true, defaultEditor: true }).extend({
    // Allow empty string in the UI select, treat as undefined later
    defaultEditor: z.union([z.enum(["markdown", "simpleMarkdown", "htmlRichText"]).optional(), z.literal("")]).optional(),
    // Include showInSidebar so CrudForm doesn't strip it on submit
    showInSidebar: z.boolean().optional()
  });
  const metadataFieldsReadOnly = entitySource === "code";
  const fields = [
    { id: "label", label: "Label", type: "text", required: true, readOnly: metadataFieldsReadOnly },
    { id: "description", label: "Description", type: "textarea", readOnly: metadataFieldsReadOnly },
    {
      id: "defaultEditor",
      label: "Default Editor (multiline)",
      type: "select",
      readOnly: metadataFieldsReadOnly,
      options: [
        { value: "", label: "Default (Markdown)" },
        { value: "markdown", label: "Markdown (UIW)" },
        { value: "simpleMarkdown", label: "Simple Markdown" },
        { value: "htmlRichText", label: "HTML Rich Text" }
      ]
    },
    ...entitySource === "custom" ? [{ id: "showInSidebar", label: "Show in sidebar", type: "checkbox" }] : []
  ];
  const renderFieldDefinitions = React.useCallback(
    () => /* @__PURE__ */ jsx(
      FieldDefinitionsEditor,
      {
        definitions: defs,
        errors: defErrors,
        deletedKeys,
        fieldsets,
        activeFieldset,
        onActiveFieldsetChange: setActiveFieldset,
        onFieldsetsChange: (next) => {
          setFieldsets(next);
          if (!next.some((fs) => fs.code === activeFieldset)) {
            setActiveFieldset(next[0]?.code ?? null);
          }
        },
        onFieldsetCodeChange: handleFieldsetCodeChange,
        onFieldsetRemoved: handleFieldsetRemoved,
        singleFieldsetPerRecord,
        onSingleFieldsetPerRecordChange: setSingleFieldsetPerRecord,
        onAddField: addField,
        onRemoveField: (index) => {
          void removeField(index);
        },
        onDefinitionChange: (index, nextDef) => {
          setDefs((arr) => arr.map((entry, idx) => idx === index ? nextDef : entry));
          validateAndSetErrorAt(index, nextDef);
        },
        onTranslate: (def) => setTranslateDef({ def, entityId }),
        onRestoreField: (key) => {
          void restoreField(key);
        },
        onReorder: (from, to) => {
          setDefs((arr) => {
            const next = [...arr];
            const [moved] = next.splice(from, 1);
            next.splice(to, 0, moved);
            return next;
          });
          setOrderDirty(true);
        },
        orderNotice: orderDirty ? { dirty: true, saving: orderSaving, message: "Reordered \u2014 will auto-save on blur" } : void 0,
        addButtonLabel: t("entities.customFields.editor.addField", "Add Field"),
        translate: t,
        listRef,
        listProps: {
          tabIndex: -1,
          onBlur: (event) => {
            const current = listRef.current;
            const next = event.relatedTarget;
            if (!current) return;
            if (!next || !current.contains(next)) {
              void saveOrderIfDirty();
            }
          }
        }
      }
    ),
    [defs, defErrors, deletedKeys, fieldsets, activeFieldset, singleFieldsetPerRecord, orderDirty, orderSaving, addField, removeField, restoreField, saveOrderIfDirty]
  );
  const definitionsGroup = { id: "definitions", title: "Field Definitions", column: 1, component: renderFieldDefinitions };
  const groups = [
    { id: "settings", title: "Entity Settings", column: 1, fields: entitySource === "custom" ? ["label", "description", "defaultEditor", "showInSidebar"] : ["label", "description", "defaultEditor"] },
    definitionsGroup
  ];
  const handleCrudFormSubmit = React.useCallback(async (vals) => {
    if (!entityId) {
      throw createCrudFormError("Invalid entity ID");
    }
    if (!validateAll()) {
      flash("Please fix validation errors in field definitions", "error");
      throw createCrudFormError("Please fix validation errors in field definitions");
    }
    if (shouldRegisterEntityMetadata(entitySource)) {
      const entityPayload = buildEntityMetadataPayload(entitySource, vals);
      if (!entityPayload) throw createCrudFormError("Validation failed");
      const callEntity = await apiCall("/api/entities/entities", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ entityId, ...entityPayload })
      });
      if (!callEntity.ok) {
        await raiseCrudError(callEntity.response, "Failed to save entity");
      }
      try {
        window.dispatchEvent(new Event("om:refresh-sidebar"));
      } catch {
      }
    }
    const defsPayload = buildDefinitionsBatchPayload({
      entityId,
      defs,
      fieldsets: buildFieldsetPayload(),
      singleFieldsetPerRecord
    });
    const callDefs = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(defsVersion),
      () => apiCall("/api/entities/definitions.batch", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(defsPayload)
      })
    );
    if (!callDefs.ok) {
      await raiseCrudError(callDefs.response, "Failed to save definitions");
    }
    setDefsVersion(readVersionToken(callDefs.result?.version));
    try {
      window.dispatchEvent(new Event("om:refresh-sidebar"));
    } catch {
    }
    await invalidateCustomFieldDefs(queryClient, entityId);
    flash("Definitions saved", "success");
  }, [buildFieldsetPayload, defs, defsVersion, entityId, entitySource, queryClient, singleFieldsetPerRecord, validateAll]);
  if (!entityId) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: "Invalid entity" }),
      /* @__PURE__ */ jsx(AlertDescription, { children: "The requested entity ID is missing or invalid." })
    ] }) }) }) });
  }
  if (embedFieldsetView) {
    return /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(
      CrudForm,
      {
        schema: entityFormSchema,
        title: `Edit fieldset: ${requestedFieldset ?? entityId}`,
        fields: [],
        groups: [definitionsGroup],
        initialValues: entityInitial,
        isLoading: entityFormLoading || loading,
        submitLabel: "Save",
        deleteVisible: false,
        backHref: void 0,
        cancelHref: void 0,
        embedded: true,
        onSubmit: handleCrudFormSubmit
      }
    ) });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      CrudForm,
      {
        schema: entityFormSchema,
        title: `Edit Entity: ${entityId}`,
        backHref: entitySource === "code" ? "/backend/entities/system" : "/backend/entities/user",
        fields,
        groups,
        initialValues: entityInitial,
        isLoading: entityFormLoading || loading,
        submitLabel: "Save",
        deleteVisible: entitySource === "custom",
        extraActions: entitySource === "custom" ? /* @__PURE__ */ jsx(Button, { variant: "outline", asChild: true, children: /* @__PURE__ */ jsx(Link, { href: `/backend/entities/user/${encodeURIComponent(entityId)}/records`, children: "Show Records" }) }) : null,
        cancelHref: entitySource === "code" ? "/backend/entities/system" : "/backend/entities/user",
        successRedirect: entitySource === "code" ? "/backend/entities/system?flash=Definitions%20saved&type=success" : "/backend/entities/user?flash=Definitions%20saved&type=success",
        onSubmit: handleCrudFormSubmit,
        onDelete: entitySource === "custom" ? async () => {
          const callDelete = await apiCall("/api/entities/entities", { method: "DELETE", headers: { "content-type": "application/json" }, body: JSON.stringify({ entityId }) });
          if (!callDelete.ok) {
            await raiseCrudError(callDelete.response, "Failed to delete entity");
          }
          flash("Entity deleted", "success");
          try {
            window.dispatchEvent(new Event("om:refresh-sidebar"));
          } catch {
          }
        } : void 0
      }
    ) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!translateDef, onOpenChange: (open) => {
      if (!open) setTranslateDef(null);
    }, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[80vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("translations.manager.translateField", "Translate field: {{key}}", { key: translateDef?.def.key ?? "" }) }) }),
      translateDef && /* @__PURE__ */ jsx(
        TranslationManager,
        {
          mode: "embedded",
          compact: true,
          entityType: "entities:custom_field_def",
          recordId: `${translateDef.entityId}:${translateDef.def.key}`,
          baseValues: translateBaseValues,
          translatableFields: translateFields
        }
      )
    ] }) })
  ] });
}
function shouldRegisterEntityMetadata(entitySource) {
  return entitySource === "custom";
}
function buildDefinitionsBatchPayload(options) {
  return {
    entityId: options.entityId,
    definitions: options.defs.filter((d) => !!d.key).map((d) => ({
      key: d.key,
      kind: d.kind,
      configJson: d.configJson,
      isActive: d.isActive !== false
    })),
    fieldsets: options.fieldsets,
    singleFieldsetPerRecord: options.singleFieldsetPerRecord
  };
}
function buildEntityMetadataPayload(entitySource, vals) {
  const partial = entitySource === "custom" ? upsertCustomEntitySchema.pick({ label: true, description: true, labelField: true, defaultEditor: true }).extend({ showInSidebar: z.boolean().optional() }) : upsertCustomEntitySchema.pick({ label: true, description: true, defaultEditor: true });
  const normalized = {
    ...vals,
    defaultEditor: typeof vals.defaultEditor === "string" && vals.defaultEditor ? vals.defaultEditor : void 0
  };
  const parsed = partial.safeParse(normalized);
  return parsed.success ? parsed.data : null;
}
export {
  buildDefinitionsBatchPayload,
  buildEntityMetadataPayload,
  EditDefinitionsPage as default,
  shouldRegisterEntityMetadata
};
//# sourceMappingURL=page.js.map
