const formatDateAsString = (value) => (value instanceof Date ? value.toISOString() : value ?? null)

function mapDealToDealCardResponse(deal) {
  return {
    id: deal.id,
    title: deal.title,
    description: deal.description || "",
    price: deal.price ?? null,
    originalPrice: deal.originalPrice ?? null,
    shippingPrice: deal.shippingPrice ?? null,

    score: deal.score,
    commentsCount: deal.commentCount,
    url:deal.url,
    status: deal.status,
    saleType: deal.saletype,
    affiliateType: deal.affiliateType,

    myVote: deal.myVote ?? 0,

    createdAt: formatDateAsString(deal.createdAt),
    updatedAt: formatDateAsString(deal.updatedAt),

    user: {
      id: deal.user.id,
      username: deal.user.username,
      avatarUrl: deal.user.avatarUrl ?? null,
    },

    seller: deal.seller
      ? {
          name: deal.seller.name,
          url: deal.seller.url ?? null,
        }
      : {
          name: deal.customSeller || "",
          url: null,
        },
    
    imageUrl: deal.images?.[0]?.imageUrl || "",
  }
}

function mapPaginatedDealsToDealCardResponse(paginated) {
  return {
    ...paginated,
    results: paginated.results.map(mapDealToDealCardResponse),
  }
}

module.exports = { mapDealToDealCardResponse,mapPaginatedDealsToDealCardResponse }
