import { root } from '@repo/core'
import { FileController } from '@repo/sdk'
import { Platform } from 'react-native'

import { handleError } from '@/hooks/use-error'

export async function uploadFile(params: { uri: string; mimeType?: string; fileName?: string }): Promise<string> {
  const { uri, mimeType, fileName } = params

  console.log('[uploadFile] 开始上传:', { uri, mimeType, fileName, platform: Platform.OS })

  const formData = new FormData()
  formData.append('file', {
    uri: uri,
    name: fileName || 'uploaded_file.jpg',
    type: mimeType || 'image/jpeg',
  } as any)

  const fileController = root.get(FileController)
  const { data, error } = await handleError(async () => await fileController.uploadS3(formData))

  if (error || !data?.data) {
    console.error('[uploadFile] 上传失败:', { error, data, uri })
    throw error || new Error('上传失败')
  }

  console.log('[uploadFile] 上传成功:', data.data)
  return data.data
}
