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

function createRedisClient() {
  return getRedisClient()
}

async function getNewDealListId(redis, newListId) {
  if (newListId) return String(newListId)
  const latest = await redis.get("deals:lists:new:latest")
  return latest ? String(latest) : null
}

async function getNewDealIds({ newListId } = {}) {
  const redis = createRedisClient()

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

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

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

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

module.exports = { getNewDealIds }
