import { useCallback, useState } from "react";
import { normalizeApiError } from "../services/http.js";

export default function useSubmitAction() {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const run = useCallback(async (fn, okMessage = "Action completed") => {
    setSubmitting(true);
    setError("");
    try {
      const out = await fn();
      return { ok: true, data: out, message: okMessage };
    } catch (err) {
      const message = normalizeApiError(err);
      setError(message);
      return { ok: false, message };
    } finally {
      setSubmitting(false);
    }
  }, []);

  return { run, submitting, error, setError };
}
