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

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

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

module.exports = { ensureSellerIdCounter, generateSellerId }
