import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type { ProductExpertReview } from '../types/expertReview'

export const EXPERT_REVIEWS_PER_PAGE = 20

export interface ExpertReviewApi {
  id: string
  businessId: string
  productId: string
  authorName: string
  authorEmail: string | null
  rate: number
  positivePoints: string[]
  negativePoints: string[]
  text: string
  isApproved: boolean
  approvedAt: string | null
  approvedBy: string | null
  approver: { id: string; firstName: string; lastName: string } | null
  createdAt: string
  updatedAt: string
}

export interface ExpertReviewsListResponse {
  items: ExpertReviewApi[]
  total: number
  page: number
  pageSize: number
}

function expertReviewsPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/expert-reviews${suffix}`
}

export function mapExpertReviewApiToUi(review: ExpertReviewApi): ProductExpertReview {
  return {
    id: review.id,
    authorName: review.authorName,
    rate: review.rate,
    positivePoints: review.positivePoints ?? [],
    negativePoints: review.negativePoints ?? [],
    text: review.text,
    approved: review.isApproved,
    createdAt: review.createdAt,
  }
}

export function formatReviewDate(iso: string, locale: 'en' | 'fa' = 'en'): string {
  return new Date(iso).toLocaleDateString(locale === 'fa' ? 'fa-IR' : 'en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

export async function listProductExpertReviews(
  productId: string,
  page = 1,
  pageSize = EXPERT_REVIEWS_PER_PAGE,
  signal?: AbortSignal,
) {
  const params = new URLSearchParams({
    productId,
    page: String(page),
    pageSize: String(pageSize),
  })

  const data = await apiRequest<ExpertReviewsListResponse>(`${expertReviewsPath()}?${params}`, {
    auth: true,
    signal,
  })

  return {
    ...data,
    items: data.items.map(mapExpertReviewApiToUi),
  }
}

export async function updateExpertReviewApproval(reviewId: string, isApproved: boolean) {
  const data = await apiRequest<{ review: ExpertReviewApi }>(expertReviewsPath(`/${reviewId}`), {
    method: 'PATCH',
    auth: true,
    body: { isApproved },
  })
  return mapExpertReviewApiToUi(data.review)
}

export async function deleteExpertReview(reviewId: string) {
  return apiRequest<{ success: boolean }>(expertReviewsPath(`/${reviewId}`), {
    method: 'DELETE',
    auth: true,
  })
}
