// adapters/responses/userProfile.adapter.js
const dealCardAdapter = require("./dealCard.adapter")
const dealCommentAdapter = require("./comment.adapter")
const publicUserAdapter = require("./publicUser.adapter") // yoksa yaz
const userProfileStatsAdapter = require("./userProfileStats.adapter")

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

function mapUserBadgeToResponse(item) {
  if (!item) return null
  return {
    badge: item.badge
      ? {
          id: item.badge.id,
          name: item.badge.name,
          iconUrl: item.badge.iconUrl ?? null,
          description: item.badge.description ?? null,
        }
      : null,
    earnedAt: formatDateAsString(item.earnedAt),
  }
}

function mapUserProfileToResponse({ user, deals, comments, stats, badges }) {
  return {
    user: publicUserAdapter.mapUserToPublicUserDetailsResponse(user),
    stats: userProfileStatsAdapter.mapUserProfileStatsToResponse(stats),
    deals: deals.map(dealCardAdapter.mapDealToDealCardResponse),
    comments: comments.map(dealCommentAdapter.mapCommentToUserCommentResponse),
    badges: Array.isArray(badges) ? badges.map(mapUserBadgeToResponse).filter(Boolean) : [],
  }
}

module.exports = { mapUserProfileToResponse }
