const prisma = require("./client")

async function findLike(commentId, userId, db) {
  const p = db || prisma
  return p.commentLike.findUnique({
    where: { commentId_userId: { commentId, userId } },
  })
}

async function findLikesByUserAndCommentIds(userId, commentIds, db) {
  const p = db || prisma
  return p.commentLike.findMany({
    where: { userId, commentId: { in: commentIds } },
    select: { commentId: true },
  })
}

async function setCommentLike({ commentId, userId, like }) {
  return prisma.$transaction(async (tx) => {
    const comment = await tx.comment.findUnique({
      where: { id: commentId },
      select: { id: true, likeCount: true },
    })
    if (!comment) throw new Error("Yorum bulunamadÄ±.")

    const existing = await findLike(commentId, userId, tx)

    if (like) {
      if (existing) {
        return { liked: true, delta: 0, likeCount: comment.likeCount }
      }
      await tx.commentLike.create({
        data: { commentId, userId },
      })
      const updated = await tx.comment.update({
        where: { id: commentId },
        data: { likeCount: { increment: 1 } },
        select: { likeCount: true },
      })
      return { liked: true, delta: 1, likeCount: updated.likeCount }
    }

    if (!existing) {
      return { liked: false, delta: 0, likeCount: comment.likeCount }
    }
    await tx.commentLike.delete({
      where: { commentId_userId: { commentId, userId } },
    })
    const updated = await tx.comment.update({
      where: { id: commentId },
      data: { likeCount: { decrement: 1 } },
      select: { likeCount: true },
    })
    return { liked: false, delta: -1, likeCount: updated.likeCount }
  })
}

module.exports = {
  findLikesByUserAndCommentIds,
  setCommentLike,
}
