//! 桌面端文件服务上传(file.1216.top)— 图片/文件 → 公开 URL
//!
//! 与小程序端 `apps/df-miniapp/src/utils/fileUpload.ts` 对称:复用 file.1216.top 的
//! `POST /upload`(multipart 'file' + X-Source 头)→ 返回公开 URL。
//! 桌面端是浏览器环境,用 fetch + FormData(区别于小程序 uni.uploadFile)。
//! file.1216.top 已确认 CORS 支持(`Access-Control-Allow-Origin: *`,X-Source 在 allow-headers)。

/** file.1216.top 上传地址(可经 appSettings 'df-file-upload-base' 覆盖) */
export const DEFAULT_FILE_UPLOAD_BASE = 'https://file.1216.top'
/** X-Source 项目标识(文件存 file.1216.top 对应目录,项目隔离) */
export const FILE_UPLOAD_SOURCE = 'devflow-desktop'

export interface UploadResult {
  url: string
}

/**
 * 上传文件到 file.1216.top,返回公开 URL。失败 reject(调用方回退 base64)。
 * 响应结构:`{"result":{"url":"https://..."},"retcode":0,"success":true}`
 */
export async function uploadFile(file: File, base?: string): Promise<UploadResult> {
  const uploadBase = base || DEFAULT_FILE_UPLOAD_BASE
  const form = new FormData()
  form.append('file', file, file.name)
  const res = await fetch(`${uploadBase}/upload`, {
    method: 'POST',
    headers: { 'X-Source': FILE_UPLOAD_SOURCE },
    body: form,
  })
  if (!res.ok) {
    throw new Error(`上传失败:HTTP ${res.status}`)
  }
  const data = (await res.json()) as { result?: { url?: string }; success?: boolean; retcode?: number }
  if (data?.success === true && data?.retcode === 0 && data?.result?.url) {
    return { url: data.result.url }
  }
  throw new Error(`上传响应异常:${JSON.stringify(data)}`)
}
