import { apiClient } from '@/shared/api/client'

export async function postProductReview(
  productId: string,
  body: { rating: number; text?: string | null; imageUrl?: string | null },
): Promise<void> {
  await apiClient.post(`products/${productId}/reviews`, body)
}

export async function uploadReviewImage(file: File): Promise<{ url: string }> {
  const fd = new FormData()
  fd.append('file', file, file.name)
  const { data } = await apiClient.post<{ url: string }>('reviews/upload-image', fd)
  return data
}

export type PublicReviewFeedItem = {
  id: string
  rating: number
  text: string | null
  imageUrl: string | null
  createdAt: string
  authorDisplay: string
  productId: string
  productTitle: string
}

export type PublicReviewsLatestResponse = {
  items: PublicReviewFeedItem[]
}

export async function fetchLatestApprovedReviews(limit = 5): Promise<PublicReviewsLatestResponse> {
  const { data } = await apiClient.get<PublicReviewsLatestResponse>('reviews/latest', {
    params: { limit },
  })
  return data
}

export type PublicProductReviewItem = {
  id: string
  rating: number
  text: string | null
  imageUrl: string | null
  createdAt: string
  authorDisplay: string
}

export type PublicProductReviewsResponse = {
  items: PublicProductReviewItem[]
  total: number
  page: number
  pageSize: number
}

export async function fetchPublicProductReviews(
  productId: string,
  params?: { page?: number; pageSize?: number },
): Promise<PublicProductReviewsResponse> {
  const { data } = await apiClient.get<PublicProductReviewsResponse>(`products/${productId}/reviews`, {
    params: { page: params?.page, pageSize: params?.pageSize },
  })
  return data
}
