"use client";
import * as React from "react";
import { useInjectionSpotEvents } from "./InjectionSpot.js";
import { GLOBAL_MUTATION_INJECTION_SPOT_ID, dispatchBackendMutationError } from "./mutationEvents.js";
import { withScopedApiRequestHeaders } from "../utils/apiCall.js";
function useGuardedMutation({
  contextId,
  blockedMessage = "Save blocked by validation",
  spotId = GLOBAL_MUTATION_INJECTION_SPOT_ID
}) {
  const { triggerEvent } = useInjectionSpotEvents(spotId);
  const lastMutationRef = React.useRef(null);
  const emitMutationSaveError = React.useCallback((error) => {
    dispatchBackendMutationError({
      contextId,
      formId: contextId,
      error
    });
  }, [contextId]);
  const runMutation = React.useCallback(async ({
    operation,
    context,
    mutationPayload
  }) => {
    const payload = mutationPayload ?? {};
    lastMutationRef.current = {
      operation,
      context,
      mutationPayload: payload
    };
    const beforeSave = await triggerEvent("onBeforeSave", payload, context);
    if (!beforeSave.ok) {
      emitMutationSaveError(beforeSave.details ?? beforeSave);
      throw new Error(beforeSave.message || blockedMessage);
    }
    try {
      const result = beforeSave.requestHeaders && Object.keys(beforeSave.requestHeaders).length > 0 ? await withScopedApiRequestHeaders(beforeSave.requestHeaders, operation) : await operation();
      try {
        await triggerEvent("onAfterSave", payload, context);
      } catch (error) {
        console.error("[useGuardedMutation] Error in onAfterSave injection event:", error);
      }
      return result;
    } catch (error) {
      emitMutationSaveError(error);
      throw error;
    }
  }, [blockedMessage, emitMutationSaveError, triggerEvent]);
  const retryLastMutation = React.useCallback(async () => {
    const lastMutation = lastMutationRef.current;
    if (!lastMutation) return false;
    try {
      await runMutation({
        operation: lastMutation.operation,
        context: lastMutation.context,
        mutationPayload: lastMutation.mutationPayload
      });
      return true;
    } catch {
      return false;
    }
  }, [runMutation]);
  return {
    runMutation,
    retryLastMutation
  };
}
export {
  useGuardedMutation
};
//# sourceMappingURL=useGuardedMutation.js.map
