import uploadFileToAlioss from '@/xiaolanbenlib/module/alioss'
import Taro from '@tarojs/taro'

const IMAGE_LIMIT = 50 * 1024 * 1024 // 50MB = 52428800 bytes
const VIDEO_LIMIT = 30 * 1024 * 1024 // 30MB
const FILE_LIMIT = 100 * 1024 * 1024 // 100MB

// Types for response
type UserInfo = { code: number; uid: string; token: string }
type UploadResult = { videoUrl: string; thumbnailUrl: string; size: number }

// Fetch user info
export async function getUserInfo(): Promise<UserInfo> {
  return {
    code: 0,
    uid:
      Taro.getStorageSync('userId') || Taro.getStorageSync('u51UserId') || '',
    token:
      Taro.getStorageSync('userToken') ||
      Taro.getStorageSync('u51UserToken') ||
      '',
  }
}

// Pick a video and upload
export async function pickAndUploadVideo(): Promise<UploadResult> {
  try {
    const res = await Taro.chooseMedia({
      mediaType: ['video'],
      sourceType: ['album'],
      count: 1,
    })

    const data = res.tempFiles[0]
    if (data.size >= VIDEO_LIMIT) {
      Taro.showToast({
        title: '视频大小超限',
        icon: 'error',
        duration: 1500,
      })
      throw new Error('Video size exceeds limit')
    }

    const imageFile = { path: data.thumbTempFilePath }
    const videoFile = { path: data.tempFilePath }

    const imageData = await uploadFileToAlioss({}, imageFile)
    const videoData = await uploadFileToAlioss({}, videoFile)

    Taro.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 1500,
    })

    return {
      videoUrl: videoData.url,
      thumbnailUrl: imageData.url,
      size: data.size,
    }
  } catch (error) {
    throw new Error('Failed to pick or upload video')
  }
}

// Pick an image and upload
export async function pickAndUploadImage(
  sourceType: Array<'album' | 'camera'> = ['album', 'camera'],
): Promise<{ url: string; size: number }> {
  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 uploadFileToAlioss({}, file)
    Taro.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 1500,
    })

    return {
      url: uploadResult.url,
      size: file.size,
    }
  } catch (error) {
    throw new Error('Failed to pick or upload image')
  }
}

// pick a file from wechat message
export async function pickAndUploadFile(): Promise<{
  title: string
  url: string
  size: number
}> {
  try {
    const res = await Taro.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['pdf'],
    })

    const file = res.tempFiles[0]
    if (file.size >= FILE_LIMIT) {
      Taro.showToast({
        title: '文件大小超过限制',
        icon: 'error',
        duration: 1500,
      })
      throw new Error('File size exceeds limit')
    }

    const uploadResult = await uploadFileToAlioss({}, file)
    Taro.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 1500,
    })

    return {
      title: file.name,
      url: uploadResult.url,
      size: file.size,
    }
  } catch (error) {
    throw new Error('Failed to pick or upload file')
  }
}
