// services/user.service.js
const userDB = require("../db/user.db")
const dealDB = require("../db/deal.db")
const commentDB = require("../db/comment.db")

async function getUserProfileByUsername(userName) {
  const username = String(userName).trim()
  if (!username) throw new Error("username zorunlu")

  const user = await userDB.findUser(
    { username },
    { select: { id: true, username: true, avatarUrl: true, createdAt: true } }
  )

  if (!user) {
    const err = new Error("Kullanıcı bulunamadı.")
    err.statusCode = 404
    throw err
  }

    const [dealAgg, totalComments, deals, comments] = await Promise.all([
      dealDB.aggregateDeals({ userId: user.id }),
      commentDB.countComments({ userId: user.id }),
      dealDB.findDeals(
        { userId: user.id },
        {
          orderBy: { createdAt: "desc" },
          take: 20,
          include: {
            user: { select: { id: true, username: true, avatarUrl: true } },
            seller: { select: { name: true, url: true } },
            images: { orderBy: { order: "asc" }, take: 1, select: { imageUrl: true } },
          },
        }
      ),
      commentDB.findComments(
        { userId: user.id },
        {
          orderBy: { createdAt: "desc" },
          take: 20,
          include: {
            user: { select: { id: true, username: true, avatarUrl: true } },
            deal: { select: { id: true, title: true } },
          },
        }
      ),
    ])

    const stats = {
      totalLikes: dealAgg?._sum?.score ?? 0,
      totalComments: totalComments ?? 0,
      totalShares: dealAgg?._count?._all ?? 0,
    }


    return { user, stats, deals, comments }

    }

module.exports = { getUserProfileByUsername }
