import Taro from '@tarojs/taro'
import { callCloud, canUseCloud } from './cloud'
import type { MediaAsset, PublishDraft } from '@/types/domain'

export async function chooseImages(currentCount: number): Promise<MediaAsset[]> {
  const remain = Math.max(0, 9 - currentCount)
  if (remain <= 0) return []

  const result = await Taro.chooseMedia({
    count: Math.min(3, remain),
    mediaType: ['image'],
    sourceType: ['album', 'camera']
  })

  return result.tempFiles.map((file, index) => ({
    id: `${Date.now()}_${index}`,
    url: file.tempFilePath,
    type: 'image'
  }))
}

// Upload any locally-chosen images to cloud storage so they persist and are
// viewable by others. Items that are already cloud fileIDs are left untouched.
export async function uploadPostMedia(media: MediaAsset[]): Promise<MediaAsset[]> {
  if (!canUseCloud()) return media
  return Promise.all(
    media.map(async item => {
      if (!item.url || item.url.startsWith('cloud://')) return item
      try {
        const ext = (item.url.split('?')[0].split('.').pop() || 'jpg').slice(0, 5)
        const cloudPath = `posts/${Date.now()}_${Math.random().toString(36).slice(2, 8)}.${ext}`
        const res = await Taro.cloud.uploadFile({ cloudPath, filePath: item.url })
        return { ...item, url: res.fileID, fileId: res.fileID }
      } catch {
        return item
      }
    })
  )
}

export async function createPost(draft: PublishDraft): Promise<{ postId: string }> {
  if (!canUseCloud()) return { postId: `local_${Date.now()}` }
  return callCloud('postCreate', draft)
}

export async function saveDraft(draft: PublishDraft): Promise<{ draftId: string; updatedAt: number }> {
  if (!canUseCloud()) return { draftId: 'local_draft', updatedAt: Date.now() }
  return callCloud('draftSave', { draft })
}

export async function getDraft(): Promise<{ draft: PublishDraft | null; updatedAt?: number }> {
  if (!canUseCloud()) return { draft: null }
  return callCloud('draftGet', {})
}

