import type {CrumbReactor} from '@crumbs/core/schemas'
import {useEffect} from 'react'

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

const NO_REACTORS: CrumbReactor[] = []

const fetchReactors = async (
  trailId: string,
  crumbId: string,
): Promise<CrumbReactor[]> => {
  const {reactors} = await unwrap(
    rpc.trails[':id'].crumbs[':crumbId'].reactions.$get({
      param: {id: trailId, crumbId},
    }),
  )
  return reactors
}

// who reacted to a crumb inside a trail, fetched on mount
export const useTrailReactors = (
  trailId: string,
  crumbId: string,
) => {
  const {data, loading, error, run} = useAsyncResource(
    fetchReactors,
    NO_REACTORS,
  )

  useEffect(() => {
    void run(trailId, crumbId)
  }, [run, trailId, crumbId])

  return {reactors: data, loading, error}
}
