import { apiClient } from '@/shared/api/client'
import { OTHER_UPLOAD_MAX_FILE_BYTES, formatOtherUploadMaxSizeHint } from '@/shared/constants/upload-limits'

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 }> {
  if (file.size > OTHER_UPLOAD_MAX_FILE_BYTES) {
    throw new Error(`Файл «${file.name}» слишком большой (максимум ${formatOtherUploadMaxSizeHint()}).`)
  }

  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
  authorId: string
  authorDisplay: string
  authorAvatar?: string | null
  authorAvatarStyle?: string | null
  product: {
    id: string
    title: string
    published: boolean
    slug: 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
  authorId: string
  authorDisplay: string
  authorAvatar?: string | null
  authorAvatarStyle?: string | null
}

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
}
