import { apiFetch, getBaseUrl } from './client'; export interface ProductReviewItem { review_id: string; product_id: string; author_name: string; rating: number; title: string; comment: string; verified_buyer: boolean; is_approved?: boolean; helpful_count: number; admin_reply?: string | null; review_date?: string | null; images: string[]; } export interface ProductReviewSummaryResponse { average_rating: number; total_reviews: number; star_distribution: Record; verified_count: number; page: number; limit: number; reviews: ProductReviewItem[]; } export interface ReviewCreatePayload { rating: number; title: string; comment: string; author_name: string; author_email?: string; image_urls?: string[]; } export const reviewService = { async getProductReviews( productId: string, page: number = 1, limit: number = 10, sort: string = 'newest' ): Promise { const params = new URLSearchParams({ page: String(page), limit: String(limit), sort, }); try { return await apiFetch( `/api/v1/storefront/reviews/${productId}?${params.toString()}` ); } catch { // Graceful fallback if no reviews yet return { average_rating: 0, total_reviews: 0, star_distribution: { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 }, verified_count: 0, page: 1, limit, reviews: [], }; } }, async submitReview( productId: string, payload: ReviewCreatePayload ): Promise { return await apiFetch( `/api/v1/storefront/reviews/${productId}`, { method: 'POST', body: JSON.stringify(payload), } ); }, async uploadReviewImage(file: File, productId: string): Promise { const baseUrl = getBaseUrl(); const formData = new FormData(); formData.append('file', file); formData.append('entity_type', 'review'); formData.append('entity_id', productId); const res = await fetch( `${baseUrl}/api/v1/files/upload?entity_type=review&entity_id=${encodeURIComponent(productId)}`, { method: 'POST', body: formData, } ); if (!res.ok) { const err = await res.json().catch(() => ({ detail: 'Upload failed' })); throw new Error(err.detail || 'Failed to upload review image'); } const data = await res.json(); return data.file_url || data.url || ''; }, };