// hooks/useUpload.ts
import { ref } from 'vue'
import { getAuthToken } from '@/utils/auth'

export function useUpload(uploadUrl: string) {
  const progress = ref(0)
  const uploading = ref(false)

  const upload = (filePath: string) => {
    uploading.value = true
    return new Promise((resolve, reject) => {
      const uploadTask = uni.uploadFile({
        url: uploadUrl,
        filePath,
        name: 'file',
        header: {
          Authorization: `Bearer ${getAuthToken()}`,
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200) resolve(data.data)
            else reject(data)
          } catch (e) {
            reject(e)
          }
        },
        fail: reject,
        complete: () => {
          uploading.value = false
        },
      })

      uploadTask.onProgressUpdate((res) => {
        progress.value = res.progress
      })
    })
  }

  return { progress, uploading, upload }
}
