/** file.1216.top 文件服务上传客户端。
 * POST /upload multipart 'file' 字段 + 'X-Source' 头 → {"result":{"url":"https://..."},"retcode":0,"success":true}
 */
import { getConfig } from '@/config'

export interface UploadResult { url: string }

/** 上传图片到 file.1216.top,返回公开 URL。失败 reject(调用方回退 base64)。 */
export function uploadImage(tempFilePath: string): Promise<UploadResult> {
  const cfg = getConfig()
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${cfg.fileUploadBaseUrl}/upload`,
      filePath: tempFilePath,
      name: 'file',
      header: { 'X-Source': cfg.fileUploadSource },
      timeout: 15000,
      success: (res) => {
        try {
          const data = JSON.parse(res.data as string)
          const url = data?.result?.url as string | undefined
          if (data?.success === true && data?.retcode === 0 && url) {
            resolve({ url })
          } else {
            reject(new Error(`上传响应异常: ${res.data}`))
          }
        } catch (e) {
          reject(e)
        }
      },
      fail: (err) => reject(err),
    })
  })
}
