const commentLikeDb = require("../db/commentLike.db")
const commentDb = require("../db/comment.db")

function parseLike(value) {
  if (typeof value === "boolean") return value
  if (typeof value === "number") return value === 1
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase()
    if (["true", "1", "yes"].includes(normalized)) return true
    if (["false", "0", "no"].includes(normalized)) return false
  }
  return null
}

async function setCommentLike({ commentId, userId, like }) {
  const cid = Number(commentId)
  if (!Number.isInteger(cid) || cid <= 0) throw new Error("GeÃ§ersiz commentId.")
  const shouldLike = parseLike(like)
  if (shouldLike === null) throw new Error("GeÃ§ersiz like.")

  // Ensure comment exists (and not deleted)
  const existing = await commentDb.findComment({ id: cid }, { select: { id: true } })
  if (!existing) throw new Error("Yorum bulunamadÄ±.")

  return commentLikeDb.setCommentLike({ commentId: cid, userId, like: shouldLike })
}

module.exports = {
  setCommentLike,
}
