import { callCloud, canUseCloud } from './cloud'
import { resolveCloudFileUrlMap } from './cloud-file'
import { mockPets, mockProfile } from './mock'
import { markStale } from '@/store/dataBus'
import { normalizeUser } from '@/utils/user'
import type { Pet, UserProfile } from '@/types/domain'

async function resolveProfileAssets(user: UserProfile, pets: Pet[]): Promise<{ user: UserProfile; pets: Pet[] }> {
  const urls = [user.avatarUrl || '', ...pets.map(pet => pet.photoUrl || '')]
  const urlMap = await resolveCloudFileUrlMap(urls)
  const readUrl = (url?: string) => {
    if (!url) return url
    return urlMap.has(url) ? urlMap.get(url) || '' : url
  }

  return {
    user: { ...user, avatarUrl: readUrl(user.avatarUrl) },
    pets: pets.map(pet => ({ ...pet, photoUrl: readUrl(pet.photoUrl) }))
  }
}

export async function getProfile(userId?: string): Promise<{ user: UserProfile; pets: Pet[] }> {
  if (!canUseCloud()) return { user: mockProfile, pets: mockPets }
  try {
    const result = await callCloud<object, { user: UserProfile | null; pets: Pet[] }>(
      'profileGet',
      userId ? { userId } : {}
    )
    if (!result.user) return { user: normalizeUser(null), pets: [] }
    return resolveProfileAssets(normalizeUser(result.user), result.pets || [])
  } catch {
    return { user: mockProfile, pets: mockPets }
  }
}

export async function updateProfile(patch: Partial<UserProfile>): Promise<UserProfile> {
  if (!canUseCloud()) {
    const user = { ...mockProfile, ...patch }
    markStale('profile')
    return user
  }
  const result = await callCloud<object, { user: UserProfile }>('profileUpdate', { patch })
  const user = (await resolveProfileAssets(normalizeUser(result.user), [])).user
  markStale('profile')
  return user
}

export async function getPetList(): Promise<Pet[]> {
  if (!canUseCloud()) return mockPets
  const result = await callCloud<object, { list: Pet[] }>('petList', {})
  return (await resolveProfileAssets(mockProfile, result.list || [])).pets
}
