import type { RatingAggregate } from '@platform-modules/commerce-reviews'
import { useReviewsClient } from './client.js'
import { reviveRatingAggregate } from './revive.js'
import { useAsyncResource } from './useAsyncResource.js'

export function useRatingAggregate(
  productId: string,
  seed?: RatingAggregate,
): {
  data: RatingAggregate | undefined
  loading: boolean
  error: Error | null
  reload: () => void
} {
  const client = useReviewsClient('useRatingAggregate')
  const key = `aggregate:${productId}`
  const fetcher = () => client.getRatingAggregate(productId).then(reviveRatingAggregate)
  const { data, loading, error, reload } = useAsyncResource<RatingAggregate>(
    fetcher,
    key,
    seed !== undefined ? { initialData: seed } : undefined,
  )
  return { data: data ?? undefined, loading, error, reload }
}
