"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, usePathname } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { createCrud, updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
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 { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { E } from "../../../../../../../../generated/entities.ids.generated.js";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import {
  createVariantInitialValues,
  normalizeOptionSchema,
  mapPriceItemToDraft,
  findInvalidVariantPriceKinds
} from "@open-mercato/core/modules/catalog/components/products/variantForm";
import {
  normalizePriceKindSummary,
  normalizeTaxRateSummary,
  mergeTaxRateSummaries
} from "@open-mercato/core/modules/catalog/components/products/productForm";
import { parseNumericInput } from "@open-mercato/core/modules/catalog/components/products/productFormUtils";
import {
  VariantBasicsSection,
  VariantOptionValuesSection,
  VariantDimensionsSection,
  VariantMetadataSection,
  VariantPricesSection,
  VariantMediaSection
} from "@open-mercato/core/modules/catalog/components/products/VariantBuilder";
import { buildAttachmentImageUrl, slugifyAttachmentFileName } from "@open-mercato/core/modules/attachments/lib/imageUrls";
import { fetchOptionSchemaTemplate } from "../../../optionSchemaClient.js";
import CreateVariantPage from "../create/page.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("catalog");
function handleVariantDeleteError(err, t) {
  if (surfaceRecordConflict(err, t)) return;
  const message = err instanceof Error && err.message ? err.message : t("catalog.variants.form.deleteError", "Failed to delete variant.");
  flash(message, "error");
}
function resolveVariantPriceLabel(prices) {
  if (!prices || typeof prices !== "object") return null;
  const entries = Object.values(prices);
  for (const entry of entries) {
    const amount = typeof entry?.amount === "string" ? entry.amount.trim() : "";
    if (!amount) continue;
    const currencyCode = typeof entry.currencyCode === "string" && entry.currencyCode.trim().length ? entry.currencyCode.trim().toUpperCase() : null;
    return currencyCode ? `${currencyCode} ${amount}` : amount;
  }
  return null;
}
function EditVariantPage({ params }) {
  const router = useRouter();
  const t = useT();
  const pathname = usePathname();
  const productId = params?.productId ? String(params.productId) : null;
  const variantId = params?.variantId ? String(params.variantId) : null;
  const isCreateSentinel = variantId === "create";
  const [priceKinds, setPriceKinds] = React.useState([]);
  const [taxRates, setTaxRates] = React.useState([]);
  const [optionDefinitions, setOptionDefinitions] = React.useState([]);
  const [initialValues, setInitialValues] = React.useState(null);
  const [existingPriceIds, setExistingPriceIds] = React.useState({});
  const [existingPriceVersions, setExistingPriceVersions] = React.useState({});
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [currentProductId, setCurrentProductId] = React.useState(productId);
  const [productTitle, setProductTitle] = React.useState("");
  const [productTaxRateId, setProductTaxRateId] = React.useState(null);
  const [productTaxRate, setProductTaxRate] = React.useState(null);
  const parseTaxRateSummary = React.useCallback(
    (item) => normalizeTaxRateSummary(
      item,
      t("catalog.products.create.taxRates.unnamed", "Untitled tax rate")
    ),
    [t]
  );
  const fetchTaxRateById = React.useCallback(
    async (taxRateId) => {
      const payload = await readApiResultOrThrow(
        `/api/sales/tax-rates?id=${encodeURIComponent(taxRateId)}&pageSize=1`,
        void 0,
        { errorMessage: t("catalog.products.create.taxRates.error", "Failed to load tax rates."), fallback: { items: [] } }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      return items.map((item) => parseTaxRateSummary(item)).find((item) => item?.id === taxRateId) ?? null;
    },
    [parseTaxRateSummary, t]
  );
  React.useEffect(() => {
    const loadPriceKinds = async () => {
      try {
        const payload = await readApiResultOrThrow(
          "/api/catalog/price-kinds?pageSize=100",
          void 0,
          { errorMessage: t("catalog.priceKinds.errors.load", "Failed to load price kinds.") }
        );
        const items = Array.isArray(payload.items) ? payload.items : [];
        setPriceKinds(items.map((item) => normalizePriceKindSummary(item)).filter((item) => !!item));
      } catch (err) {
        logger.error("catalog.price-kinds.fetch failed", { err });
        setPriceKinds([]);
      }
    };
    loadPriceKinds().catch(() => {
    });
  }, [t]);
  React.useEffect(() => {
    const loadTaxRates = async () => {
      try {
        const payload = await readApiResultOrThrow(
          "/api/sales/tax-rates?pageSize=200",
          void 0,
          { errorMessage: t("catalog.products.create.taxRates.error", "Failed to load tax rates."), fallback: { items: [] } }
        );
        const items = Array.isArray(payload.items) ? payload.items : [];
        setTaxRates(
          items.map((item) => parseTaxRateSummary(item)).filter((item) => item !== null)
        );
      } catch (err) {
        logger.error("sales.tax-rates.fetch failed", { err });
        setTaxRates([]);
      }
    };
    loadTaxRates().catch(() => {
    });
  }, [parseTaxRateSummary, t]);
  React.useEffect(() => {
    const ids = [initialValues?.taxRateId, productTaxRateId].filter(
      (value) => typeof value === "string" && value.length > 0
    );
    const missingIds = ids.filter((id) => !taxRates.some((rate) => rate.id === id));
    if (!missingIds.length) return;
    Promise.all(missingIds.map((id) => fetchTaxRateById(id).catch(() => null))).then((selectedRates) => {
      setTaxRates(
        (current) => selectedRates.reduce(
          (next, selected) => mergeTaxRateSummaries(next, selected),
          current
        )
      );
    }).catch(() => {
    });
  }, [fetchTaxRateById, initialValues?.taxRateId, productTaxRateId, taxRates]);
  React.useEffect(() => {
    if (!variantId || isCreateSentinel || priceKinds.length === 0) return;
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const variantRes = await apiCall(
          `/api/catalog/variants?id=${encodeURIComponent(variantId)}&page=1&pageSize=1`
        );
        if (!variantRes.ok) {
          if (variantRes.status === 404) {
            if (!cancelled) setIsNotFound(true);
            return;
          }
          throw new Error(t("catalog.variants.form.errors.load", "Failed to load variant."));
        }
        const record = Array.isArray(variantRes.result?.items) ? variantRes.result?.items?.[0] : void 0;
        if (!record) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        const resolvedProductId = typeof record.product_id === "string" ? record.product_id : typeof record.productId === "string" ? record.productId : currentProductId;
        if (resolvedProductId) setCurrentProductId(resolvedProductId);
        const metadata = typeof record.metadata === "object" && record.metadata ? { ...record.metadata } : {};
        const [attachments, priceDrafts, productRes] = await Promise.all([
          fetchVariantAttachments(variantId),
          loadVariantPrices(variantId, priceKinds),
          resolvedProductId ? apiCall(
            `/api/catalog/products?id=${encodeURIComponent(resolvedProductId)}&page=1&pageSize=1`
          ) : Promise.resolve(null)
        ]);
        const priceIdMap = {};
        const priceVersionMap = {};
        Object.entries(priceDrafts).forEach(([kindId, draft]) => {
          if (draft.priceId) {
            priceIdMap[kindId] = draft.priceId;
            priceVersionMap[kindId] = draft.updatedAt ?? null;
          }
        });
        setExistingPriceIds(priceIdMap);
        setExistingPriceVersions(priceVersionMap);
        const customDefaults = extractCustomFieldEntries(record);
        let loadedOptionDefinitions = [];
        if (resolvedProductId) {
          if (productRes?.ok) {
            const product = Array.isArray(productRes.result?.items) ? productRes.result?.items?.[0] : void 0;
            if (product) {
              setProductTitle(typeof product.title === "string" ? product.title : "");
              const taxRateId = typeof product.tax_rate_id === "string" ? product.tax_rate_id : typeof product.taxRateId === "string" ? product.taxRateId : null;
              const taxRateValueRaw = typeof product.tax_rate === "number" ? product.tax_rate : typeof product.tax_rate === "string" ? Number(product.tax_rate) : typeof product.taxRate === "number" ? product.taxRate : typeof product.taxRate === "string" ? Number(product.taxRate) : null;
              const taxRateValue = Number.isFinite(taxRateValueRaw) ? Number(taxRateValueRaw) : null;
              setProductTaxRateId(taxRateId);
              setProductTaxRate(taxRateValue);
              const productMetadata = product.metadata ?? {};
              const optionSchemaId = typeof product.option_schema_id === "string" ? product.option_schema_id : typeof product.optionSchemaId === "string" ? product.optionSchemaId : null;
              let schemaSource = productMetadata.optionSchema ?? productMetadata.option_schema;
              if (optionSchemaId) {
                const template = await fetchOptionSchemaTemplate(optionSchemaId);
                if (template?.schema?.options) {
                  schemaSource = template.schema.options.map((option) => ({
                    code: option.code,
                    label: option.label,
                    values: Array.isArray(option.choices) ? option.choices.map((choice) => ({
                      id: choice.code ?? void 0,
                      label: choice.label ?? choice.code ?? ""
                    })) : []
                  }));
                }
              }
              loadedOptionDefinitions = normalizeOptionSchema(schemaSource);
              setOptionDefinitions(loadedOptionDefinitions);
            }
          }
        }
        const variantTaxRateId = typeof record.tax_rate_id === "string" ? record.tax_rate_id : typeof record.taxRateId === "string" ? record.taxRateId : null;
        if (!cancelled) {
          const optionValues = typeof record.option_values === "object" && record.option_values ? { ...record.option_values } : typeof record.optionValues === "object" && record.optionValues ? { ...record.optionValues } : {};
          const normalizedOptionValues = reconcileOptionValues(optionValues, loadedOptionDefinitions);
          const defaultMediaId = typeof record.default_media_id === "string" ? record.default_media_id : typeof record.defaultMediaId === "string" ? record.defaultMediaId : attachments[0]?.id ?? null;
          const defaultMediaUrl = typeof record.default_media_url === "string" ? record.default_media_url : typeof record.defaultMediaUrl === "string" ? record.defaultMediaUrl : "";
          const base = createVariantInitialValues();
          setInitialValues({
            ...base,
            id: variantId,
            mediaDraftId: variantId,
            name: typeof record.name === "string" ? record.name : "",
            sku: typeof record.sku === "string" ? record.sku : "",
            barcode: typeof record.barcode === "string" ? record.barcode : "",
            gtinType: typeof record.gtin_type === "string" ? record.gtin_type : typeof record.gtinType === "string" ? record.gtinType : null,
            hsCode: typeof record.hs_code === "string" ? record.hs_code : typeof record.hsCode === "string" ? record.hsCode : "",
            isDefault: record.is_default === true || record.isDefault === true,
            isActive: record.is_active !== false && record.isActive !== false,
            optionValues: normalizedOptionValues,
            metadata,
            mediaItems: attachments,
            defaultMediaId,
            defaultMediaUrl,
            prices: priceDrafts,
            taxRateId: variantTaxRateId,
            customFieldsetCode: typeof record.custom_fieldset_code === "string" ? record.custom_fieldset_code : typeof record.customFieldsetCode === "string" ? record.customFieldsetCode : null,
            updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : typeof record.updated_at === "string" ? record.updated_at : null,
            ...customDefaults
          });
        }
      } catch (err) {
        logger.error("catalog.variants.load.failed", { err });
        if (!cancelled) {
          const message = err instanceof Error && err.message ? err.message : t("catalog.variants.form.errors.load", "Failed to load variant.");
          setError(message);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [variantId, t, currentProductId, priceKinds]);
  const groups = React.useMemo(() => {
    const list = [
      {
        id: "general",
        column: 1,
        title: t("catalog.variants.form.general", "General"),
        component: ({ values, setValue, errors }) => /* @__PURE__ */ jsx(VariantBasicsSection, { values, setValue, errors })
      },
      {
        id: "metadata",
        column: 1,
        title: t("catalog.products.edit.metadata.title", "Metadata"),
        description: t("catalog.products.edit.metadata.hint", "Attach structured key/value pairs for integrations."),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantMetadataSection, { values, setValue, showIntro: false, embedded: true })
      },
      {
        id: "prices",
        column: 1,
        title: t("catalog.variants.form.pricesLabel", "Prices"),
        description: t("catalog.variants.form.pricesHint", "Populate list prices per price kind."),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(
          VariantPricesSection,
          {
            values,
            setValue,
            priceKinds,
            taxRates,
            showHeader: false,
            embedded: true
          }
        )
      },
      {
        id: "media",
        column: 1,
        title: t("catalog.variants.form.media", "Media"),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantMediaSection, { values, setValue, showLabel: false })
      }
    ];
    if (optionDefinitions.length) {
      list.push({
        id: "options",
        column: 2,
        title: t("catalog.variants.form.options", "Option values"),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(
          VariantOptionValuesSection,
          {
            values,
            setValue,
            optionDefinitions,
            showHeading: false
          }
        )
      });
    }
    list.push({
      id: "dimensions",
      column: 2,
      title: t("catalog.variants.form.dimensions", "Dimensions & weight"),
      component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantDimensionsSection, { values, setValue, showHeading: false })
    });
    list.push({
      id: "custom",
      column: 2,
      title: t("catalog.variants.form.customFields", "Custom attributes"),
      kind: "customFields"
    });
    return list;
  }, [optionDefinitions, priceKinds, t, taxRates]);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "catalog.variant",
      resourceId: isCreateSentinel ? null : variantId,
      updatedAt: initialValues?.updatedAt ?? null,
      data: initialValues,
      path: pathname
    })
  );
  if (isCreateSentinel) {
    if (!productId) {
      return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "rounded border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive", children: t("catalog.variants.form.errors.productMissing", "Product identifier is missing.") }) }) });
    }
    return /* @__PURE__ */ jsx(CreateVariantPage, { params: { productId } });
  }
  if (!variantId || !currentProductId) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "rounded border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive", children: t("catalog.variants.form.errors.variantMissing", "Variant identifier is missing.") }) }) });
  }
  const formTitle = productTitle ? t("catalog.variants.form.editTitleFor", "Edit variant \u2022 {{title}}").replace("{{title}}", productTitle) : t("catalog.variants.form.editTitle", "Edit variant");
  const productVariantsHref = `/backend/catalog/products/${currentProductId}#variants`;
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("catalog.variants.form.errors.notFound", "Variant not found."),
        backHref: productVariantsHref,
        backLabel: t("catalog.variants.form.actions.backToProduct", "Back to product variants")
      }
    ) }) });
  }
  if (error && !loading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: formTitle,
      backHref: productVariantsHref,
      versionHistory: { resourceKind: "catalog.variant", resourceId: variantId ? String(variantId) : "" },
      extraActions: /* @__PURE__ */ jsx(
        SendObjectMessageDialog,
        {
          object: {
            entityModule: "catalog",
            entityType: "variant",
            entityId: variantId,
            previewData: {
              title: typeof initialValues?.name === "string" && initialValues.name.trim().length ? initialValues.name : variantId,
              metadata: {
                [t("catalog.variants.form.skuLabel")]: typeof initialValues?.sku === "string" && initialValues.sku.trim().length ? initialValues.sku : "-",
                [t("catalog.variants.form.pricesLabel")]: resolveVariantPriceLabel(initialValues?.prices) ?? "-"
              }
            }
          },
          viewHref: `/backend/catalog/products/${currentProductId}/variants/${variantId}`
        }
      ),
      fields: [],
      groups,
      entityId: E.catalog.catalog_product_variant,
      customFieldsetBindings: { [E.catalog.catalog_product_variant]: { valueKey: "customFieldsetCode" } },
      initialValues: initialValues ?? void 0,
      isLoading: loading,
      loadingMessage: t("catalog.variants.form.loading", "Loading variant..."),
      submitLabel: t("catalog.variants.form.save", "Save changes"),
      cancelHref: productVariantsHref,
      onSubmit: async (values) => {
        const name = values.name?.trim();
        if (!name) {
          const message = t("catalog.variants.form.errors.nameRequired", "Provide the variant name.");
          throw createCrudFormError(message, { name: message });
        }
        const invalidPriceKinds = findInvalidVariantPriceKinds(priceKinds, values.prices);
        if (invalidPriceKinds.length) {
          const message = t("catalog.variants.form.errors.invalidPrice", "Provide a valid non-negative price.");
          throw createCrudFormError(message, { prices: message });
        }
        const resolveTaxRateValue = (taxRateId) => {
          if (!taxRateId) return null;
          const match = taxRates.find((rate) => rate.id === taxRateId);
          return typeof match?.rate === "number" && Number.isFinite(match.rate) ? match.rate : null;
        };
        const resolvedTaxRateId = values.taxRateId ?? productTaxRateId ?? null;
        const resolvedTaxRateValue = values.taxRateId && resolvedTaxRateId ? resolveTaxRateValue(resolvedTaxRateId) : productTaxRateId ? resolveTaxRateValue(productTaxRateId) ?? productTaxRate : productTaxRate ?? null;
        const metadata = typeof values.metadata === "object" && values.metadata ? { ...values.metadata } : {};
        const defaultMediaEntry = values.defaultMediaId ? (Array.isArray(values.mediaItems) ? values.mediaItems : []).find((item) => item.id === values.defaultMediaId) : null;
        const defaultMediaUrl = defaultMediaEntry ? buildAttachmentImageUrl(defaultMediaEntry.id, {
          slug: slugifyAttachmentFileName(defaultMediaEntry.fileName)
        }) : null;
        const payload = {
          id: variantId,
          productId: currentProductId,
          name,
          sku: values.sku?.trim() || void 0,
          barcode: values.barcode?.trim() || void 0,
          gtinType: values.gtinType ?? null,
          hsCode: values.hsCode?.trim() || null,
          isDefault: Boolean(values.isDefault),
          isActive: values.isActive !== false,
          optionValues: Object.keys(values.optionValues ?? {}).length ? values.optionValues : void 0,
          metadata,
          defaultMediaId: values.defaultMediaId ?? void 0,
          defaultMediaUrl: defaultMediaUrl ?? void 0,
          customFieldsetCode: values.customFieldsetCode?.trim().length ? values.customFieldsetCode : void 0,
          taxRateId: resolvedTaxRateId,
          taxRate: resolvedTaxRateValue
        };
        const customFields = collectCustomFieldValues(values);
        if (Object.keys(customFields).length) payload.customFields = customFields;
        await updateCrud("catalog/variants", payload);
        await syncVariantPricesUpdate({
          priceKinds,
          priceDrafts: values.prices ?? {},
          existingPriceIds,
          existingPriceVersions,
          productId: currentProductId,
          variantId,
          taxRates,
          taxRateId: values.taxRateId,
          productTaxRateId,
          productTaxRate
        });
        flash(t("catalog.variants.form.updated", "Variant updated."), "success");
        router.push(productVariantsHref);
      },
      onDelete: async () => {
        try {
          await deleteCrud("catalog/variants", variantId, {
            errorMessage: t("catalog.variants.form.deleteError", "Failed to delete variant.")
          });
        } catch (err) {
          handleVariantDeleteError(err, t);
          throw err;
        }
        flash(t("catalog.variants.form.deleted", "Variant deleted."), "success");
        router.push(productVariantsHref);
      },
      deleteRedirect: productVariantsHref
    }
  ) }) });
}
function reconcileOptionValues(optionValues, optionDefinitions) {
  if (!optionValues || !optionDefinitions.length) {
    return optionValues ?? {};
  }
  const remaining = new Map(Object.entries(optionValues));
  const normalized = {};
  for (const option of optionDefinitions) {
    const code = option.code?.trim();
    if (!code) continue;
    if (remaining.has(code)) {
      const value = remaining.get(code);
      if (value !== void 0) {
        normalized[code] = value;
      }
      remaining.delete(code);
      continue;
    }
    const matchKey = findOptionKeyByValue(remaining, option.values);
    if (matchKey) {
      const value = remaining.get(matchKey);
      if (value !== void 0) {
        normalized[code] = value;
      }
      remaining.delete(matchKey);
    }
  }
  remaining.forEach((value, key) => {
    if (normalized[key] === void 0) {
      normalized[key] = value;
    }
  });
  return normalized;
}
function findOptionKeyByValue(candidates, optionValues) {
  if (!optionValues.length) return null;
  const matches = [];
  candidates.forEach((value, key) => {
    if (optionValues.some((entry) => entry.label === value)) {
      matches.push(key);
    }
  });
  return matches.length === 1 ? matches[0] : null;
}
async function fetchVariantAttachments(variantId) {
  try {
    const res = await apiCall(
      `/api/attachments?entityId=${encodeURIComponent(E.catalog.catalog_product_variant)}&recordId=${encodeURIComponent(variantId)}`
    );
    if (!res.ok) return [];
    return Array.isArray(res.result?.items) ? res.result?.items ?? [] : [];
  } catch (err) {
    logger.error("catalog.variants.attachments.load", { err });
    return [];
  }
}
async function loadVariantPrices(variantId, priceKinds) {
  const kindDisplayModes = new Map(priceKinds.map((k) => [k.id, k.displayMode]));
  const drafts = {};
  const pageSize = 100;
  let page = 1;
  try {
    while (true) {
      const res = await apiCall(
        `/api/catalog/prices?variantId=${encodeURIComponent(variantId)}&page=${page}&pageSize=${pageSize}`
      );
      if (!res.ok) break;
      const items = Array.isArray(res.result?.items) ? res.result?.items : [];
      for (const item of items) {
        const draft = mapPriceItemToDraft(item, kindDisplayModes);
        if (draft) drafts[draft.priceKindId] = draft;
      }
      if (items.length < pageSize) break;
      page += 1;
    }
  } catch (err) {
    logger.error("catalog.variants.prices.load", { err });
  }
  return drafts;
}
async function syncVariantPricesUpdate({
  priceKinds,
  priceDrafts,
  existingPriceIds,
  existingPriceVersions,
  productId,
  variantId,
  taxRates,
  taxRateId,
  productTaxRateId,
  productTaxRate
}) {
  const selectedTaxRate = taxRates.find((rate) => rate.id === taxRateId) ?? null;
  const fallbackProductTaxRate = !selectedTaxRate && productTaxRateId ? taxRates.find((rate) => rate.id === productTaxRateId) ?? null : null;
  const resolvedTaxRateValue = selectedTaxRate?.rate ?? fallbackProductTaxRate?.rate ?? (Number.isFinite(productTaxRate ?? null) ? productTaxRate ?? null : null);
  const resolvedTaxRateId = (selectedTaxRate ?? fallbackProductTaxRate)?.id ?? null;
  for (const kind of priceKinds) {
    const draft = priceDrafts?.[kind.id];
    const amount = typeof draft?.amount === "string" ? draft.amount.trim() : "";
    const existingId = draft?.priceId ?? existingPriceIds[kind.id];
    const lockVersion = draft?.updatedAt ?? existingPriceVersions[kind.id] ?? null;
    if (!amount) {
      if (existingId) {
        try {
          await withScopedApiRequestHeaders(
            buildOptimisticLockHeader(lockVersion),
            () => deleteCrud("catalog/prices", existingId)
          );
        } catch (err) {
          logger.error("catalog.prices.delete", { err });
        }
      }
      continue;
    }
    const numeric = parseNumericInput(amount);
    if (!Number.isFinite(numeric) || numeric < 0) continue;
    const payload = {
      productId,
      variantId,
      priceKindId: kind.id,
      currencyCode: kind.currencyCode ?? void 0
    };
    if (resolvedTaxRateId) payload.taxRateId = resolvedTaxRateId;
    else if (typeof resolvedTaxRateValue === "number" && Number.isFinite(resolvedTaxRateValue)) payload.taxRate = resolvedTaxRateValue;
    if (kind.displayMode === "including-tax") payload.unitPriceGross = numeric;
    else payload.unitPriceNet = numeric;
    if (existingId) {
      await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(lockVersion),
        () => updateCrud("catalog/prices", { id: existingId, ...payload })
      );
    } else {
      await createCrud("catalog/prices", payload);
    }
  }
}
export {
  EditVariantPage as default,
  handleVariantDeleteError
};
//# sourceMappingURL=page.js.map
