const { updateCommentLikeInRedisByDeal } = require("./redis/commentCache.service")
const { queueCommentLikeUpdate } = require("./redis/dbSync.service")
const { getDealIdByCommentId, getOrCacheDeal } = require("./redis/dealCache.service")
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("Gecersiz commentId.")
  const shouldLike = parseLike(like)
  if (shouldLike === null) throw new Error("Gecersiz like.")

  let dealId = await getDealIdByCommentId(cid)
  if (!dealId) {
    const fallback = await commentDB.findComment(
      { id: cid },
      { select: { id: true, dealId: true, deletedAt: true } }
    )
    if (!fallback || fallback.deletedAt) throw new Error("Yorum bulunamadi.")
    dealId = fallback.dealId
  }

  const deal = await getOrCacheDeal(dealId, { ttlSeconds: 15 * 60 })
  if (!deal) throw new Error("Deal bulunamadi.")
  if (deal.status !== "ACTIVE" && deal.status !== "EXPIRED") {
    throw new Error("Bu deal icin yorum begenisi acilamaz.")
  }

  const redisResult = await updateCommentLikeInRedisByDeal({
    dealId,
    commentId: cid,
    userId,
    like: shouldLike,
  }).catch((err) => {
    console.error("Redis comment like update failed:", err?.message || err)
    return { liked: shouldLike, delta: 0, likeCount: 0 }
  })

  queueCommentLikeUpdate({
    commentId: cid,
    userId,
    like: shouldLike,
    createdAt: new Date().toISOString(),
  }).catch((err) => console.error("DB sync commentLike queue failed:", err?.message || err))

  return redisResult
}

module.exports = {
  setCommentLike,
}
