import { showToast } from 'vant'
import { getStorage } from '@/utils/storage'

// 当前使用 mock 模式
const USE_MOCK = false

export interface ApiResponse<T = any> {
  code: number
  msg: string
  data: T
}

export async function request<T = any>(url: string, options?: RequestInit): Promise<ApiResponse<T>> {
  if (USE_MOCK) {
    throw new Error('Mock mode — use mock services directly')
  }

  const token = getStorage('token')
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  }

  try {
    const baseUrl = import.meta.env.VITE_API_BASE || '/dgapi'
    const res = await fetch(`${baseUrl}${url}`, {
      ...options,
      headers: { ...headers, ...(options?.headers as Record<string, string> || {}) },
    })
    const json = await res.json()
    if (json.code !== 200) {
      showToast(json.msg || '请求失败')
    }
    return json
  } catch (err: any) {
    showToast(err.message || '网络错误')
    throw err
  }
}
