import { ref, type Ref } from 'vue'

interface AdminQueryOptions<T> {
  fetchFn: () => Promise<T>
  immediate?: boolean
  initialData?: T
}

interface AdminQueryResult<T> {
  loading: Ref<boolean>
  error: Ref<string | null>
  data: Ref<T>
  load: () => Promise<void>
}

export function useAdminQuery<T>(options: AdminQueryOptions<T>): AdminQueryResult<T> {
  const loading = ref(false)
  const error = ref<string | null>(null)
  const data = ref<T>(options.initialData as T) as Ref<T>

  async function load() {
    loading.value = true
    error.value = null
    try {
      data.value = await options.fetchFn()
    } catch (e) {
      error.value = e instanceof Error ? e.message : '加载失败'
      console.error('Failed to load data:', e)
    } finally {
      loading.value = false
    }
  }

  if (options.immediate !== false) {
    load()
  }

  return { loading, error, data, load }
}

// 保持向后兼容
export const useAdminTable = useAdminQuery
