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

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

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

module.exports = { ensureCategoryIdCounter, generateCategoryId }
