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

function createRedisClient() {
  return getRedisClient()
}

async function getTrendingDealListId(redis, trendingListId) {
  if (trendingListId) return String(trendingListId)
  const latest = await redis.get("lists:trending:latest")
  return latest ? String(latest) : null
}

async function getTrendingDealIds({ trendingListId } = {}) {
  const redis = createRedisClient()

  try {
    const listId = await getTrendingDealListId(redis, trendingListId)
    if (!listId) return { trendingListId: null, dealIds: [] }

    const key = `lists:trending:${listId}`
    const raw = await redis.call("JSON.GET", key, "$.dealIds")
    if (!raw) return { trendingListId: listId, dealIds: [] }

    const parsed = JSON.parse(raw)
    const dealIds = Array.isArray(parsed) ? parsed[0] : []

    return {
      trendingListId: listId,
      dealIds: Array.isArray(dealIds) ? dealIds.map((id) => Number(id)) : [],
    }
  } finally {}
}

module.exports = { getTrendingDealIds }
