// src/composables/useRequest.ts
import { ref } from 'vue'
import service from '@/utils/request'

interface UseRequestOptions<T> {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  params?: any
  data?: any
  immediate?: boolean
  onSuccess?: (data: T) => void
  onError?: (error: any) => void
}

export function useRequest<T = any>(options: UseRequestOptions<T>) {
  const { url, method = 'GET', params, data, immediate = true, onSuccess, onError } = options

  const loading = ref(false)
  const response = ref<T | null>(null)
  const error = ref<any>(null)

  const run = async () => {
    loading.value = true
    error.value = null
    try {
      const res = await service({ url, method, params, data })
      response.value = res
      onSuccess?.(res)
    } catch (err) {
      error.value = err
      onError?.(err)
    } finally {
      loading.value = false
    }
  }

  if (immediate) {
    run()
  }

  return { loading, response, error, run }
}