import { createContext, useContext } from 'react'
import type { Review } from '@platform-modules/commerce-reviews'
import { ReviewsProviderError } from './errors.js'

export interface ReviewListOpts {
  cursor?: string
  limit?: number
}

export interface SubmitReviewWire {
  productId: string
  purchaseId: string
  rating: number
  body?: string | null
}

export type OptimisticReview = Omit<Review, 'id' | 'userId'> & { id: null; userId?: string }

export interface ReviewsClient {
  listReviews(productId: string, opts?: ReviewListOpts): Promise<unknown>
  getRatingAggregate(productId: string): Promise<unknown>
  submitReview(input: SubmitReviewWire): Promise<unknown>
}

export const ReviewsContext = createContext<ReviewsClient | null>(null)

export function useReviewsClient(hook: string): ReviewsClient {
  const c = useContext(ReviewsContext)
  if (!c) throw new ReviewsProviderError(hook)
  return c
}
