import { getToken } from '@/utils/auth'

export async function apiFetch(path: string, options: RequestInit = {}) {
  const token = getToken()
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(options.headers as Record<string, string> || {}),
  }
  if (token) headers['Authorization'] = `Bearer ${token}`
  const res = await fetch(path, {
    ...options,
    headers,
    credentials: 'include',
  })
  return res
}

export async function apiJSON<T>(path: string, options: RequestInit = {}) {
  const res = await apiFetch(path, options)
  if (!res.ok) throw new Error(`请求失败: ${res.status}`)
  const ct = res.headers.get('content-type') || ''
  if (ct.includes('application/json')) return res.json() as Promise<T> 
  const text = await res.text()
  // 文本成功兼容
  if (/success/i.test(text)) return ({ success: true } as unknown) as T
  throw new Error(text || '请求失败')
}
