import type {RecommendedCrumb} from '@crumbs/core/schemas'

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

const NO_RECS: RecommendedCrumb[] = []

const fetchFriendRecs = async (coords: {
  lat: number
  lng: number
}): Promise<RecommendedCrumb[]> => {
  const {crumbs} = await unwrap(
    rpc.recommendations.crumbs.$get({
      query: {lat: String(coords.lat), lng: String(coords.lng)},
    }),
  )
  return crumbs
}

export const useFriendRecs = () => {
  const {data, loading, error, run, reset} = useAsyncResource(
    fetchFriendRecs,
    NO_RECS,
  )
  return {recs: data, loading, error, fetch: run, reset}
}
