import type { Page } from '@platform-modules/commerce-reviews'
import type { ReviewListOpts } from './client.js'
import { useReviewsClient } from './client.js'
import { type PublicReview, reviveReviewPage } from './revive.js'
import { useAsyncResource } from './useAsyncResource.js'

export function useReviewList(
  productId: string,
  opts?: ReviewListOpts,
  seed?: Page<PublicReview>,
): {
  data: Page<PublicReview> | undefined
  loading: boolean
  error: Error | null
  reload: () => void
} {
  const client = useReviewsClient('useReviewList')
  const key = `list:${productId}:${opts?.cursor ?? ''}:${opts?.limit ?? ''}`
  const fetcher = () => client.listReviews(productId, opts).then(reviveReviewPage)
  const { data, loading, error, reload } = useAsyncResource<Page<PublicReview>>(
    fetcher,
    key,
    seed !== undefined ? { initialData: seed } : undefined,
  )
  return { data: data ?? undefined, loading, error, reload }
}
