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

const MISS_HASH_KEY = "cache:misses"

function shouldLog() {
  return String(process.env.CACHE_MISS_LOG || "").trim() === "1"
}

function buildField({ key, label }) {
  const ctx = getRequestContext()
  const ctxPart = ctx ? `${ctx.method} ${ctx.path}` : "unknown"
  const labelPart = label ? `| ${label}` : ""
  return `${ctxPart} | ${key}${labelPart}`
}

async function recordCacheMiss({ key, label }) {
  if (!key) return
  const field = buildField({ key, label })
  const redis = getRedisClient()
  try {
    await redis.hincrby(MISS_HASH_KEY, field, 1)
    if (shouldLog()) {
      console.log(`[cache-miss] ${field}`)
    }
  } catch (_) {
    // ignore
  }
}

module.exports = {
  recordCacheMiss,
  MISS_HASH_KEY,
}
