const { Worker } = require("bullmq")
const Redis = require("ioredis")
const { getRedisConnectionOptions } = require("../services/redis/connection")

const NEW_DEAL_TTL_SECONDS = 12 * 60 * 60
const NEW_DEAL_LIMIT = 1000

function createRedisClient() {
  return new Redis(getRedisConnectionOptions())
}

function parseSearchResults(results = []) {
  const ids = []
  for (let i = 1; i < results.length; i += 2) {
    const key = results[i]
    const value = results[i + 1]
    try {
      const [deal] = JSON.parse(value[1])
      ids.push(Number(deal.id))
    } catch {
      const idFromKey = key.split(":")[2]
      if (idFromKey) ids.push(Number(idFromKey))
    }
  }
  return ids
}

async function buildNewDealList() {
  const redis = createRedisClient()

  try {
    const now = Date.now()
    const query = "@status:{ACTIVE}"

    const results = await redis.call(
      "FT.SEARCH",
      "idx:data:deals",
      query,
      "SORTBY",
      "createdAtTs",
      "DESC",
      "LIMIT",
      "0",
      String(NEW_DEAL_LIMIT),
      "DIALECT",
      "3",
      "RETURN",
      "1",
      "$"
    )

    const dealIds = parseSearchResults(results)

    const runId = String(now)
    const payload = {
      id: runId,
      createdAt: new Date(now).toISOString(),
      total: dealIds.length,
      dealIds,
    }

    const key = `lists:new:${runId}`
    await redis.call("JSON.SET", key, "$", JSON.stringify(payload))
    await redis.expire(key, NEW_DEAL_TTL_SECONDS)
    await redis.set("lists:new:latest", runId, "EX", NEW_DEAL_TTL_SECONDS)

    return { id: runId, total: dealIds.length }
  } catch (error) {
    console.error("❌ buildNewDealList Hatası:", error.message)
    throw error
  } finally {
    redis.disconnect()
  }
}

async function handler() {
  return buildNewDealList()
}

function startNewDealListWorker() {
  const worker = new Worker("newdeal-list", handler, {
    connection: getRedisConnectionOptions(),
    concurrency: 1,
  })

  worker.on("completed", (job) => {
    console.log(`✅ New Deal Listesi Bitti. Bulunan ID Sayısı: ${job.returnvalue?.total}`)
  })

  worker.on("failed", (job, err) => {
    console.error(`❌ New Deal Worker Hatası!`, err.message)
  })

  return worker
}

module.exports = { startNewDealListWorker }
