"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { z } from "zod";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { ErrorMessage, LoadingMessage } from "@open-mercato/ui/backend/detail";
import { useRecordsEntityGuard } from "@open-mercato/core/modules/entities/components/useRecordsEntityGuard";
const defaultCreateRecordRequest = async (payload) => {
  await createCrud("entities/records", payload);
};
async function submitCustomEntityRecord(options) {
  const { entityId, values, createRecord = defaultCreateRecordRequest, messages } = options;
  if (!entityId || !entityId.trim()) {
    const message = messages?.entityIdRequired ?? "Entity identifier is required";
    throw createCrudFormError(message, { entityId: message });
  }
  await createRecord({ entityId, values });
}
function CreateRecordPage({ params }) {
  const t = useT();
  const entityId = decodeURIComponent(params?.entityId || "");
  const guard = useRecordsEntityGuard(entityId);
  if (guard === "blocked") {
    return /* @__PURE__ */ jsx(ErrorMessage, { label: t("entities.userEntities.records.errors.systemEntity", "This entity is system-managed. Records are available for custom entities only.") });
  }
  if (guard === "checking") {
    return /* @__PURE__ */ jsx(LoadingMessage, { label: t("entities.userEntities.records.loading", "Loading records...") });
  }
  return /* @__PURE__ */ jsx(CreateRecordPageInner, { params });
}
function CreateRecordPageInner({ params }) {
  const t = useT();
  const router = useRouter();
  const entityId = decodeURIComponent(params?.entityId || "");
  const schema = React.useMemo(() => z.object({
    // Dynamic: all fields are optional; keep unknown keys
  }).passthrough(), []);
  const fields = [];
  return /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("entities.userEntities.records.form.createTitle", "Create record"),
      backHref: `/backend/entities/user/${encodeURIComponent(entityId)}/records`,
      schema,
      fields,
      entityId,
      customEntity: true,
      submitLabel: t("entities.userEntities.records.form.submitCreate", "Create"),
      cancelHref: `/backend/entities/user/${encodeURIComponent(entityId)}/records`,
      onSubmit: async (values) => {
        await submitCustomEntityRecord({
          entityId,
          values,
          messages: {
            entityIdRequired: t("entities.userEntities.records.errors.entityIdRequired", "Entity identifier is required")
          }
        });
        router.push(`/backend/entities/user/${encodeURIComponent(entityId)}/records`);
      }
    }
  );
}
export {
  CreateRecordPage as default,
  submitCustomEntityRecord
};
//# sourceMappingURL=page.js.map
