import api from './index.js'

/**
 * 文件相关API接口
 */

// 获取文件上传预签名URL
export const getPresignedUrl = (data) => {
  return api.post('/oss/presigned-url', data)
}

// 获取POST签名版本4
export const getPostSignature = (data) => {
  return api.post('/oss/post-signature', data, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

// 上传文件到COS
export const uploadFileToCos = async (file, userId) => {
  try {
    // 获取用户ID，如果没有传入则尝试从store中获取
    const finalUserId = userId || (typeof getUserId === 'function' ? getUserId() : 'anonymous')
    
    const postSignatureResult = await getPostSignature({
      fileName: file.name,
      userId: finalUserId
    })
    
    if (postSignatureResult.code !== 200) {
      throw new Error(postSignatureResult.message || '获取上传签名失败')
    }
    
    const signatureData = postSignatureResult.data
    const formData = new FormData()
    const fileKey = signatureData.dir + Date.now() + '_' + file.name
    
    // COS POST 表单上传必需字段
    formData.append('key', fileKey)
    formData.append('policy', signatureData.policy)
    formData.append('q-sign-algorithm', signatureData['q-sign-algorithm'])
    formData.append('q-ak', signatureData['q-ak'])
    formData.append('q-key-time', signatureData['q-key-time'])
    formData.append('q-signature', signatureData['q-signature'])
    formData.append('file', file)

    const uploadResponse = await fetch(signatureData.host, { method: 'POST', body: formData })
    if (!uploadResponse.ok) {
      const errorText = await uploadResponse.text()
      throw new Error(`文件上传失败: HTTP ${uploadResponse.status} - ${errorText}`)
    }
    
    // 返回文件访问URL
    const fileUrl = `${signatureData.host}/${fileKey}`
    return { url: fileUrl, key: fileKey }
  } catch (error) {
    console.error('COS 文件上传失败:', error)
    throw error
  }
}

// 保留旧函数名作为别名，便于兼容
export const uploadFileToOss = uploadFileToCos 