import { describe, it, expect } from 'vitest'
import { useApiRequest } from '../useApiRequest'

describe('useApiRequest', () => {
  it('starts with null data, false loading, null error', () => {
    const { data, loading, error } = useApiRequest(() => Promise.resolve('ok'))
    expect(data.value).toBeNull()
    expect(loading.value).toBe(false)
    expect(error.value).toBeNull()
  })

  it('execute sets data and resets error on success', async () => {
    const { data, error, loading, execute } = useApiRequest(() => Promise.resolve('hello'))
    const result = await execute()
    expect(result).toBe('hello')
    expect(data.value).toBe('hello')
    expect(error.value).toBeNull()
    expect(loading.value).toBe(false)
  })

  it('execute sets error on failure', async () => {
    const { data, error, execute } = useApiRequest(() => Promise.reject(new Error('fail')))
    const result = await execute()
    expect(result).toBeNull()
    expect(data.value).toBeNull()
    expect(error.value).toBe('fail')
  })

  it('loading is true during execution', async () => {
    let resolvePromise!: () => void
    const fetcher = () => new Promise<string>(r => { resolvePromise = () => r('done') })
    const { loading, execute } = useApiRequest(fetcher)
    const promise = execute()
    expect(loading.value).toBe(true)
    resolvePromise()
    await promise
    expect(loading.value).toBe(false)
  })

  it('extracts detail from axios-like error shape', async () => {
    const axiosError = { response: { data: { detail: '配额超限' } } }
    const { error, execute } = useApiRequest(() => Promise.reject(axiosError))
    await execute()
    expect(error.value).toBe('配额超限')
  })

  it('returns readonly refs', () => {
    const { data, loading, error } = useApiRequest(() => Promise.resolve('ok'))
    expect((data as any).value).toBeNull()
    expect((loading as any).value).toBe(false)
    expect((error as any).value).toBeNull()
  })
})
