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

const BADGES_KEY = "data:badges"

function createRedisClient() {
  return getRedisClient()
}

function normalizeBadge(badge) {
  if (!badge?.id) return null
  return {
    id: badge.id,
    name: badge.name,
    iconUrl: badge.iconUrl ?? null,
    description: badge.description ?? null,
  }
}

async function setBadgesInRedis(badges = []) {
  const items = (Array.isArray(badges) ? badges : [])
    .map(normalizeBadge)
    .filter(Boolean)
  if (!items.length) return 0
  const redis = createRedisClient()
  try {
    const pipeline = redis.pipeline()
    items.forEach((badge) => {
      pipeline.hset(BADGES_KEY, String(badge.id), JSON.stringify(badge))
    })
    await pipeline.exec()
    return items.length
  } finally {}
}

async function setBadgeInRedis(badge) {
  const payload = normalizeBadge(badge)
  if (!payload) return false
  await setBadgesInRedis([payload])
  return true
}

async function getBadgesFromRedis() {
  const redis = createRedisClient()
  try {
    const raw = await redis.hvals(BADGES_KEY)
    if (!raw?.length) return []
    const badges = []
    raw.forEach((item) => {
      try {
        const parsed = JSON.parse(item)
        if (parsed?.id) badges.push(parsed)
      } catch {
        return
      }
    })
    return badges
  } finally {}
}

async function ensureBadgesCached() {
  const cached = await getBadgesFromRedis()
  if (cached.length) return cached
  const badges = await badgeDb.listBadges()
  if (badges.length) await setBadgesInRedis(badges)
  return badges
}

module.exports = {
  BADGES_KEY,
  getBadgesFromRedis,
  setBadgesInRedis,
  setBadgeInRedis,
  ensureBadgesCached,
}
