const prisma = require("../../db/client")
const { ensureCounterAtLeast, nextId } = require("./idGenerator.service")
const COMMENT_ID_KEY = "data:ids:comment"

async function ensureCommentIdCounter() {
  const latest = await prisma.comment.findFirst({
    select: { id: true },
    orderBy: { id: "desc" },
  })
  const maxId = latest?.id ?? 0
  await ensureCounterAtLeast(COMMENT_ID_KEY, maxId)
}

async function generateCommentId() {
  try {
    return await nextId(COMMENT_ID_KEY)
  } catch {
    const latest = await prisma.comment.findFirst({
      select: { id: true },
      orderBy: { id: "desc" },
    })
    return (latest?.id ?? 0) + 1
  }
}

module.exports = { ensureCommentIdCounter, generateCommentId }
