import { callCloud, canUseCloud } from './cloud'
import { resolveCloudFileUrlMap } from './cloud-file'
import { mockNearbyPets } from './mock'
import type { GeoPoint, NearbyPet } from '@/types/domain'

function filterNearbyPets(list: NearbyPet[], filter: string): NearbyPet[] {
  if (filter === 'dog' || filter === 'cat') return list.filter(pet => pet.species === filter)
  if (filter === 'online') return list.filter(pet => pet.online)
  return list
}

async function resolveNearbyPetAssets(list: NearbyPet[]): Promise<NearbyPet[]> {
  const urlMap = await resolveCloudFileUrlMap(list.map(pet => pet.photoUrl || ''))
  const readUrl = (url?: string) => {
    if (!url) return url
    return urlMap.has(url) ? urlMap.get(url) || '' : url
  }

  return list.map(pet => ({ ...pet, photoUrl: readUrl(pet.photoUrl) }))
}

export async function getNearbyPets(location?: GeoPoint, filter = 'all'): Promise<NearbyPet[]> {
  // Mock is only for local/offline dev. When the cloud is configured we trust it
  // and surface a real empty state on failure — never silently show fake pets.
  if (!canUseCloud()) return filterNearbyPets(mockNearbyPets, filter)
  try {
    const result = await callCloud<object, { list: NearbyPet[] }>('nearbyPets', {
      location,
      filters: { type: filter }
    })
    return resolveNearbyPetAssets(filterNearbyPets(result.list || [], filter))
  } catch {
    return []
  }
}

export async function updateLocation(location: GeoPoint | null, visible: boolean): Promise<boolean> {
  if (!canUseCloud()) return true
  const result = await callCloud<object, { ok: boolean }>('locationUpdate', { location, visible })
  return result.ok
}

export async function likeNearbyPet(petId: string): Promise<{ matched: boolean }> {
  if (!canUseCloud()) return { matched: petId.length % 2 === 0 }
  return callCloud('matchLike', { petId })
}
