import request from '@/api/request'

interface UploadResult {
  success: boolean
  message: string
  url: string
}

/**
 * 上传团课封面图片（通过后端API上传到阿里云OSS，base64方式）
 * @param file 图片文件
 * @returns OSS访问地址
 */
export async function uploadCourseImage(file: File): Promise<string> {
  const base64 = await fileToBase64(file)
  const ext = file.name.split('.').pop() || 'png'

  const result = await request.post<unknown, UploadResult>(
    '/api/groupCourse/upload/cover',
    { image: base64, filename: file.name, extension: ext },
  )

  if (result.success && result.url) {
    return result.url
  }

  throw new Error(result.message || '上传失败')
}

function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      // 去掉 data:image/xxx;base64, 前缀
      const base64 = result.split(',')[1]
      if (!base64) {
        reject(new Error('读取文件失败'))
        return
      }
      resolve(base64)
    }
    reader.onerror = () => reject(new Error('读取文件失败'))
    reader.readAsDataURL(file)
  })
}

/**
 * 将OSS原始URL转为后端代理URL，用于前端安全展示图片
 * @param ossUrl OSS原始访问地址
 * @returns 代理URL
 */
export function getProxyUrl(ossUrl: string): string {
  if (!ossUrl) return ''
  return `/api/groupCourse/cover-image/proxy?url=${encodeURIComponent(ossUrl)}`
}
