import type {PlaceRef} from '@crumbs/core/schemas'
import * as Location from 'expo-location'

import {useAsyncResource} from '@/hooks/use-async-resource'
import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'

const NO_PLACES: PlaceRef[] = []

const resolveCoords = async (coords?: {lat: number; lng: number}) => {
  if (coords) return coords
  const {status} = await Location.requestForegroundPermissionsAsync()
  if (status !== 'granted') {
    throw new Error('Location permission denied')
  }
  const position = await Location.getCurrentPositionAsync({})
  return {
    lat: position.coords.latitude,
    lng: position.coords.longitude,
  }
}

const fetchNearby = async (coords?: {
  lat: number
  lng: number
}): Promise<PlaceRef[]> => {
  const {lat, lng} = await resolveCoords(coords)
  const {places} = await unwrap(
    rpc.places.nearby.$get({
      query: {lat: String(lat), lng: String(lng)},
    }),
  )
  return places
}

export const useNearbyPlaces = () => {
  const {data, loading, error, run, reset} = useAsyncResource(
    fetchNearby,
    NO_PLACES,
  )
  return {places: data, loading, error, fetch: run, reset}
}
