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

const PROFILE_KEY_PREFIX = "users:profile:"
const DEFAULT_TTL_SECONDS = 5 * 60

function createRedisClient() {
  return getRedisClient()
}

function normalizeUserName(userName) {
  const normalized = String(userName || "").trim().toLowerCase()
  return normalized || null
}

async function getUserProfileFromRedis(userName) {
  const keyName = normalizeUserName(userName)
  if (!keyName) return null
  const redis = createRedisClient()
  try {
    const raw = await redis.call("JSON.GET", `${PROFILE_KEY_PREFIX}${keyName}`)
    if (!raw) {
      await recordCacheMiss({ key: `${PROFILE_KEY_PREFIX}${keyName}`, label: "user-profile" })
      return null
    }
    return JSON.parse(raw)
  } catch {
    return null
  } finally {}
}

async function setUserProfileInRedis(userName, payload, { ttlSeconds = DEFAULT_TTL_SECONDS } = {}) {
  const keyName = normalizeUserName(userName)
  if (!keyName || !payload) return false
  const redis = createRedisClient()
  try {
    const key = `${PROFILE_KEY_PREFIX}${keyName}`
    await redis.call("JSON.SET", key, "$", JSON.stringify(payload))
    const ttl = Number(ttlSeconds)
    if (Number.isFinite(ttl) && ttl > 0) {
      await redis.expire(key, ttl)
    }
    return true
  } catch {
    return false
  } finally {}
}

module.exports = {
  getUserProfileFromRedis,
  setUserProfileInRedis,
}
