import Taro from '@tarojs/taro'
import { uploadFile } from './http'
import { EUploadFileScene } from "@/consts/enum";
const IMAGE_LIMIT = 50 * 1024 * 1024 // 50MB = 52428800 bytes
const VIDEO_LIMIT = 30 * 1024 * 1024 // 30MB
const FILE_LIMIT = 100 * 1024 * 1024 // 100MB

export async function pickAndUploadImage(
  sourceType: Array<'album' | 'camera'> = ['album', 'camera'],
  scene: EUploadFileScene
): Promise<{ url: string; size: number }| null> {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed', 'original'],
      sourceType,
    })

    const file = res.tempFiles[0]
    if (file.size >= IMAGE_LIMIT) {
      Taro.showToast({
        title: '图片大小超限',
        icon: 'error',
        duration: 1500,
      })
      throw new Error('Image size exceeds limit')
    }
    const uploadResult = await uploadFile(
      file.path,
      scene,
    );

    Taro.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 1500,
    })
    if(uploadResult?.publicUrl){
      return {
        url: uploadResult?.publicUrl,
        size: file.size,
      }
    }
    return null
  } catch (error) {
    throw new Error('Failed to pick or upload image')
  }
}