import axios from 'axios'
import OSS from 'ali-oss'
import { getSTSToken } from '@/api/base'

let ossInstance = null

// 获取STS Token的包装函数
async function getOSSConfig() {
  try {
    const { data } = await getSTSToken()
    return {
      ...data,
      accessKeyId: data.AccessKeyId,
      accessKeySecret: data.AccessKeySecret,
      stsToken: data.SecurityToken
    }
  } catch (error) {
    handleError(error, 'Failed to retrieve STS token')
  }
}

// 创建OSS实例
async function createOSSInstance() {
  if (ossInstance) {
    return ossInstance
  }
  try {
    const config = await getOSSConfig()
    ossInstance = new OSS({
      bucket: 'zxts-book-file',
      ...config,
      refreshSTSToken: async () => {
        return await getOSSConfig()
      },
      refreshSTSTokenInterval: 14 * 60 * 1000
    })
    return ossInstance
  } catch (error) {
    handleError(error, 'Failed to create OSS instance')
  }
}

// 上传文件
export async function uploadFile(file) {
  try {
    const oss = await createOSSInstance()
    const fileExt = file.name?.substring(file.name.lastIndexOf('.')) || '.png'
    const fileName = `${new Date().getTime()}-${Math.random() * 1000}${fileExt}`
    const result = await oss.put(fileName, file)
    return result.url
  } catch (error) {
    handleError(error, 'Failed to upload file')
  }
}

// 上传通过URL获取的文件
export async function uploadFileByUrl(url) {
  try {
    const res = await axios.get(url, { responseType: 'blob' })
    return await uploadFile(res.data)
  } catch (error) {
    handleError(error, 'Failed to upload file from URL')
  }
}

// 通用错误处理函数
function handleError(error, message) {
  console.error(message, error)
  throw new Error(`${message}: ${error.message}`)
}
