import { notifyError, notifySuccess } from 'src/helpers';
import { Ref } from 'vue';

export interface RunAsyncTaskOptions {
  successMessage?: string;
  errorMessage?: string;
}

export function useRunAsyncTask<T = any>(loading: Ref<boolean>, refetch?: () => void) {
  const runTask = async (task: (...args: any) => Promise<T>, options: RunAsyncTaskOptions = {}) => {
    loading.value = true;
    try {
      const result = await task();
      refetch?.();
      if (options.successMessage) {
        notifySuccess(options.successMessage);
      }
      return result;
    } catch (error) {
      notifyError(error, options.errorMessage);
    } finally {
      loading.value = false;
    }
  };

  return runTask;
}
