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

type Suggestions = {fromPlace: string[]; recent: string[]}

const NO_SUGGESTIONS: Suggestions = {fromPlace: [], recent: []}

const fetchSuggestions = async (
  category?: string,
): Promise<Suggestions> => {
  const {fromPlace, recent} = await unwrap(
    rpc.crumbs['tag-suggestions'].$get({
      query: category ? {category} : {},
    }),
  )
  return {fromPlace, recent}
}

export const useTagSuggestions = () => {
  const {data, loading, error, run, reset} = useAsyncResource(
    fetchSuggestions,
    NO_SUGGESTIONS,
  )
  return {...data, loading, error, fetch: run, reset}
}
