import Taro from '@tarojs/taro'
import { callCloud, canUseCloud } from './cloud'
import { resolveCloudFileUrl } from './cloud-file'
import { mockPets } from './mock'
import { markStale } from '@/store/dataBus'
import type { Pet } from '@/types/domain'

// Upload a chosen pet photo temp file to cloud storage and return its fileID.
export async function uploadPetPhoto(tempPath: string): Promise<string> {
  if (!tempPath || !canUseCloud() || !Taro.cloud) return ''
  const ext = tempPath.split('.').pop()?.split('?')[0] || 'png'
  const cloudPath = `pets/${Date.now()}-${Math.floor(Math.random() * 1e6)}.${ext}`
  const uploaded = await Taro.cloud.uploadFile({ cloudPath, filePath: tempPath })
  return uploaded.fileID
}

export async function getPet(petId: string): Promise<Pet | null> {
  if (!petId) return null
  if (!canUseCloud()) return mockPets.find(p => p._id === petId) || null
  try {
    const result = await callCloud<object, { list: Pet[] }>('petList', {})
    const pet = result.list.find(p => p._id === petId) || null
    return pet ? { ...pet, photoUrl: await resolveCloudFileUrl(pet.photoUrl) } : null
  } catch {
    return null
  }
}

export async function savePet(pet: Partial<Pet>): Promise<string> {
  if (!canUseCloud()) {
    markStale('profile')
    return pet._id || `local_${Date.now()}`
  }
  const result = await callCloud<object, { petId: string }>('petSave', { pet })
  markStale('profile')
  return result.petId
}

export async function deletePet(petId: string): Promise<boolean> {
  if (!canUseCloud()) {
    markStale('profile')
    return true
  }
  const result = await callCloud<object, { ok: boolean }>('petDelete', { petId })
  if (result.ok) markStale('profile')
  return result.ok
}
