import { ref } from "vue";

export function useSubmitHandler(onSuccess) {
  const loading = ref(false);
  const serverErrors = ref({});

  const execute = async (apiCallThunk) => {
    loading.value = true;
    serverErrors.value = {};

    try {
      const response = await apiCallThunk();

      if (onSuccess && typeof onSuccess === "function") {
        onSuccess(response);
      }
    } catch (error) {
      if (error.response?.status === 422) {
        const errors = error.response.data.errors || {};
        for (const key in errors) {
          serverErrors.value[key] = errors[key][0];
        }
      } else {
        console.error(
          "An unexpected error occurred in useSubmitHandler:",
          error,
        );
        throw error;
      }
    } finally {
      loading.value = false;
    }
  };

  return {
    loading,
    serverErrors,
    execute,
  };
}
