// hooks/useRequest.ts
import { ref } from 'vue'

interface IUseRequestOptions<T> {
  immediate?: boolean
  initialData?: T
}

export function useRequest<T>(
  func: () => Promise<T>,
  options: IUseRequestOptions<T> = { immediate: false },
) {
  const loading = ref(false)
  const error = ref<any>(null)
  const data = ref<T | undefined>(options.initialData)

  const run = async () => {
    loading.value = true
    error.value = null
    try {
      const res = await func()
      data.value = res
      return res
    } catch (err) {
      error.value = err
      throw err
    } finally {
      loading.value = false
    }
  }

  options.immediate && run()

  return { loading, error, data, run }
}
