const { getRedisClient } = require("./client")

function createRedisClient() {
  return getRedisClient()
}

async function ensureCounterAtLeast(key, minValue) {
  const redis = createRedisClient()
  try {
    const currentRaw = await redis.get(key)
    const current = currentRaw ? Number(currentRaw) : 0
    if (!Number.isFinite(current) || current < minValue) {
      await redis.set(key, String(minValue))
      return minValue
    }
    return current
  } finally {}
}

async function nextId(key) {
  const redis = createRedisClient()
  try {
    const value = await redis.incr(key)
    return Number(value)
  } finally {}
}

module.exports = { ensureCounterAtLeast, nextId }
