"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter, useParams, usePathname } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiFetch, withScopedApiHeaders } from "@open-mercato/ui/backend/utils/api";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { readJsonSafe } from "@open-mercato/ui/backend/utils/serverErrors";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import {
  businessRuleFormSchema,
  createFormGroups,
  createFieldDefinitions
} from "../../../components/formConfig.js";
import { ConditionBuilder } from "../../../components/ConditionBuilder.js";
import { ActionBuilder } from "../../../components/ActionBuilder.js";
import { buildRulePayload, parseRuleToFormValues } from "../../../components/utils/formHelpers.js";
function EditBusinessRulePage() {
  const router = useRouter();
  const params = useParams();
  const pathname = usePathname();
  let ruleId;
  if (params?.slug && Array.isArray(params.slug)) {
    ruleId = params.slug[1];
  } else if (params?.id) {
    ruleId = Array.isArray(params.id) ? params.id[0] : params.id;
  }
  const t = useT();
  const { organizationId, tenantId } = useOrganizationScopeDetail();
  const { data: rule, isLoading, error } = useQuery({
    queryKey: ["business_rule", ruleId],
    queryFn: async () => {
      const response = await apiFetch(`/api/business_rules/rules/${ruleId}`);
      if (!response.ok) {
        throw new Error(t("business_rules.errors.fetchFailed"));
      }
      const result = await response.json();
      return result;
    },
    enabled: !!ruleId
  });
  const initialValues = React.useMemo(() => {
    if (rule) {
      return parseRuleToFormValues(rule);
    }
    return null;
  }, [rule]);
  const handleSubmit = async (values) => {
    const effectiveTenantId = rule?.tenantId || tenantId;
    const effectiveOrgId = rule?.organizationId || organizationId;
    if (!effectiveTenantId || !effectiveOrgId) {
      throw new Error(t("business_rules.errors.missingTenantOrOrg"));
    }
    const payload = buildRulePayload(values, effectiveTenantId, effectiveOrgId, void 0);
    const updateRule = () => apiFetch("/api/business_rules/rules", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...payload,
        id: ruleId
      })
    });
    const headers = buildOptimisticLockHeader(rule?.updatedAt ?? rule?.updated_at ?? null);
    const response = Object.keys(headers).length ? await withScopedApiHeaders(headers, updateRule) : await updateRule();
    if (!response.ok) {
      const body = await readJsonSafe(response) ?? {};
      const message = typeof body.error === "string" && body.error || typeof body.message === "string" && body.message || t("business_rules.errors.updateFailed");
      throw new CrudHttpError(response.status, { ...body, error: message });
    }
    router.push("/backend/rules");
    router.refresh();
  };
  const fields = React.useMemo(() => createFieldDefinitions(t), [t]);
  const formGroups = React.useMemo(
    () => createFormGroups(t, ConditionBuilder, ActionBuilder),
    [t]
  );
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "business_rules.rule",
      resourceId: ruleId ?? null,
      updatedAt: rule?.updatedAt ?? rule?.updated_at ?? null,
      data: rule ?? null,
      path: pathname
    })
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
      /* @__PURE__ */ jsx("span", { children: t("business_rules.rules.edit.loading") })
    ] }) }) });
  }
  if (error || !rule) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
      /* @__PURE__ */ jsx("p", { children: t("business_rules.errors.loadFailed") }),
      /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx(Link, { href: "/backend/rules", children: t("business_rules.rules.backToList") }) })
    ] }) }) });
  }
  if (!initialValues) {
    return null;
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("business_rules.rules.edit.title"),
      backHref: "/backend/rules",
      schema: businessRuleFormSchema,
      fields,
      initialValues,
      optimisticLockUpdatedAt: rule?.updatedAt ?? rule?.updated_at ?? null,
      onSubmit: handleSubmit,
      cancelHref: "/backend/rules",
      groups: formGroups,
      submitLabel: t("business_rules.rules.form.update")
    },
    ruleId
  ) }) });
}
export {
  EditBusinessRulePage as default
};
//# sourceMappingURL=page.js.map
