import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'

const USE_MOCK = false

export async function uploadImage(file: File): Promise<string> {
  if (USE_MOCK) {
    return new Promise((resolve) => {
      const reader = new FileReader()
      reader.onload = () => resolve(reader.result as string)
      reader.readAsDataURL(file)
    })
  }

  const formData = new FormData()
  formData.append('file', file)

  const userStore = useUserStore()
  const headers: Record<string, string> = {}
  if (userStore.token) {
    headers['Authorization'] = `Bearer ${userStore.token}`
  }

  const baseUrl = import.meta.env.VITE_API_BASE || '/dgapi'
  const res = await fetch(`${baseUrl}/mobile/upload/image`, {
    method: 'POST',
    headers,
    body: formData,
  })
  const json = await res.json()
  if (json.code !== 200) {
    showToast(json.msg || '上传失败')
    throw new Error(json.msg || '上传失败')
  }
  return json.data.url
}
