import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export interface FavoriteListing {
  favoriteId: string
  productId: string
  createdAt: string
  productTitle: string
  productNameFa: string
  productImage: string | null
  productTotalStock: number
  variantCount: number
  displayPrice: number | null
  displayDiscountedPrice: number | null
  showFestival: boolean
}

export interface FavoritesListResponse {
  items: FavoriteListing[]
  total: number
  page: number
  pageSize: number
}

export interface ListFavoritesParams {
  page?: number
  pageSize?: number
}

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

export async function listFavorites(params: ListFavoritesParams = {}, signal?: AbortSignal) {
  const q = new URLSearchParams()
  if (params.page !== undefined) q.set('page', String(params.page))
  if (params.pageSize !== undefined) q.set('pageSize', String(params.pageSize))

  const query = q.toString()
  const path = `${businessPath()}${query ? `?${query}` : ''}`
  return apiRequest<FavoritesListResponse>(path, { auth: true, signal })
}

export async function removeFavorite(productId: string) {
  return apiRequest<{ message: string }>(businessPath(`/${productId}`), {
    method: 'DELETE',
    auth: true,
  })
}
