import {
  RulesFormField
} from "./chunk-PLDGQ5PO.js";
import "./chunk-AEFDAU3Y.js";
import "./chunk-AW77UWCZ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import {
  usePromotion,
  usePromotionAddRules,
  usePromotionRemoveRules,
  usePromotionUpdateRules,
  useUpdatePromotion
} from "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import "./chunk-O4STPJR2.js";
import "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/promotions/common/edit-rules/edit-rules.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx
import { toast } from "@medusajs/ui";

// src/pages/promotions/common/edit-rules/components/edit-rules-form/edit-rules-form.tsx
import { useState } from "react";
import { Button } from "@medusajs/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";

// src/pages/promotions/common/edit-rules/components/edit-rules-form/form-schema.ts
import i18n from "i18next";
import { z } from "zod";
var EditRules = z.object({
  type: z.string().optional(),
  rules: z.array(
    z.object({
      id: z.string().optional(),
      attribute: z.string().min(1, { message: i18n.t("promotions.form.required") }),
      operator: z.string().min(1, { message: i18n.t("promotions.form.required") }),
      values: z.union([
        z.number().min(1, { message: i18n.t("promotions.form.required") }),
        z.string().min(1, { message: i18n.t("promotions.form.required") }),
        z.array(z.string()).min(1, { message: i18n.t("promotions.form.required") })
      ]),
      required: z.boolean().optional(),
      disguised: z.boolean().optional(),
      field_type: z.string().optional()
    })
  ),
  application_method: z.object({
    target_type: z.enum(["order", "shipping_methods", "items"])
  })
});

// src/pages/promotions/common/edit-rules/components/edit-rules-form/edit-rules-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var EditRulesForm = ({
  promotion,
  ruleType,
  handleSubmit,
  isSubmitting
}) => {
  const { t } = useTranslation();
  const [rulesToRemove, setRulesToRemove] = useState([]);
  const form = useForm({
    defaultValues: {
      rules: [],
      type: promotion.type,
      application_method: {
        target_type: promotion.application_method?.target_type
      }
    },
    resolver: zodResolver(EditRules)
  });
  const handleFormSubmit = form.handleSubmit(handleSubmit(rulesToRemove));
  return /* @__PURE__ */ jsx(
    RouteDrawer.Form,
    {
      form,
      "data-testid": `promotion-edit-rules-form-${ruleType}`,
      children: /* @__PURE__ */ jsxs(
        KeyboundForm,
        {
          onSubmit: handleFormSubmit,
          className: "flex h-full flex-col overflow-hidden",
          children: [
            /* @__PURE__ */ jsx(
              RouteDrawer.Body,
              {
                "data-testid": `promotion-edit-rules-form-body-${ruleType}`,
                className: "flex-1 overflow-y-auto",
                children: /* @__PURE__ */ jsx(
                  RulesFormField,
                  {
                    form,
                    ruleType,
                    setRulesToRemove,
                    rulesToRemove,
                    promotion,
                    formType: "edit"
                  }
                )
              }
            ),
            /* @__PURE__ */ jsx(
              RouteDrawer.Footer,
              {
                "data-testid": `promotion-edit-rules-form-footer-${ruleType}`,
                children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
                  /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(
                    Button,
                    {
                      size: "small",
                      variant: "secondary",
                      disabled: isSubmitting,
                      "data-testid": `promotion-edit-rules-form-cancel-button-${ruleType}`,
                      children: t("actions.cancel")
                    }
                  ) }),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      size: "small",
                      type: "submit",
                      isLoading: isSubmitting,
                      "data-testid": `promotion-edit-rules-form-save-button-${ruleType}`,
                      children: t("actions.save")
                    }
                  )
                ] })
              }
            )
          ]
        }
      )
    }
  );
};

// src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/utils.ts
var getRuleValue = (rule) => {
  if (rule.field_type === "number") {
    return parseInt(rule.values);
  }
  return rule.values;
};

// src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx
import { ClientError } from "@mercurjs/client";
import { jsx as jsx2 } from "react/jsx-runtime";
var EditRulesWrapper = ({
  promotion,
  rules,
  ruleType
}) => {
  const { handleSuccess } = useRouteModal();
  const { mutateAsync: updatePromotion } = useUpdatePromotion(promotion.id);
  const { mutateAsync: addPromotionRules } = usePromotionAddRules(
    promotion.id,
    ruleType
  );
  const { mutateAsync: removePromotionRules } = usePromotionRemoveRules(
    promotion.id,
    ruleType
  );
  const { mutateAsync: updatePromotionRules, isPending } = usePromotionUpdateRules(promotion.id, ruleType);
  const handleSubmit = (rulesToRemove) => {
    return async function(data) {
      const applicationMethodData = {};
      const { rules: allRules = [] } = data;
      const disguisedRules = allRules.filter((rule) => rule.disguised);
      const disguisedRulesToRemove = rulesToRemove?.filter((r) => r.disguised) || [];
      for (const rule of disguisedRules) {
        applicationMethodData[rule.attribute] = getRuleValue(rule);
      }
      for (const rule of disguisedRulesToRemove) {
        applicationMethodData[rule.attribute] = null;
      }
      const rulesData = allRules.filter((rule) => !rule.disguised);
      const rulesToCreate = rulesData.filter(
        (rule) => !("id" in rule)
      );
      const rulesToUpdate = rulesData.filter(
        (rule) => typeof rule.id === "string"
      );
      try {
        if (Object.keys(applicationMethodData).length) {
          await updatePromotion({
            application_method: applicationMethodData
          });
        }
        rulesToCreate.length && await addPromotionRules({
          rules: rulesToCreate.map((rule) => {
            return {
              attribute: rule.attribute,
              operator: rule.operator,
              values: rule.values
            };
          })
        });
        rulesToRemove?.length && await removePromotionRules({
          rule_ids: rulesToRemove.map((r) => r.id).filter(Boolean)
        });
        rulesToUpdate.length && await updatePromotionRules({
          rules: rulesToUpdate.map((rule) => {
            return {
              id: rule.id,
              attribute: rule.attribute,
              operator: rule.operator,
              values: rule.values
            };
          })
        });
        handleSuccess();
      } catch (error) {
        const message = error instanceof ClientError ? error.message.replace(
          /(\w+_\w+)/g,
          (match) => `"${match.replace(/_/g, " ")}"`
        ) : "An error occurred";
        toast.error(message);
      }
    };
  };
  return /* @__PURE__ */ jsx2(
    EditRulesForm,
    {
      promotion,
      rules,
      ruleType,
      handleSubmit,
      isSubmitting: isPending
    }
  );
};

// src/pages/promotions/common/edit-rules/edit-rules.tsx
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var EditRules2 = () => {
  const params = useParams();
  const allowedParams = [
    "rules" /* RULES */,
    "buy-rules" /* BUY_RULES */,
    "target-rules" /* TARGET_RULES */
  ];
  if (!allowedParams.includes(params.ruleType)) {
    throw "invalid page";
  }
  const { t } = useTranslation2();
  const ruleType = params.ruleType;
  const id = params.id;
  const rules = [];
  const { promotion, isPending: isLoading, isError, error } = usePromotion(id);
  if (promotion) {
    if (ruleType === "rules" /* RULES */) {
      rules.push(...promotion.rules || []);
    } else if (ruleType === "target-rules" /* TARGET_RULES */) {
      rules.push(...promotion?.application_method?.target_rules || []);
    } else if (ruleType === "buy-rules" /* BUY_RULES */) {
      rules.push(...promotion.application_method?.buy_rules || []);
    }
  }
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { "data-testid": `promotion-edit-rules-${ruleType}`, children: [
    /* @__PURE__ */ jsx3(RouteDrawer.Header, { "data-testid": `promotion-edit-rules-header-${ruleType}`, children: /* @__PURE__ */ jsx3(Heading, { "data-testid": `promotion-edit-rules-heading-${ruleType}`, children: t(`promotions.edit.${ruleType}.title`) }) }),
    !isLoading && promotion && /* @__PURE__ */ jsx3(
      EditRulesWrapper,
      {
        promotion,
        rules,
        ruleType
      }
    )
  ] });
};
export {
  EditRules2 as Component
};
