import { Client } from "discord.js"
import { timeBomb } from "@workshop/shared/utils"
import { DateTime } from "luxon"

const timeout = 1000 * 60 * 10 // 10 minutes
export const keepThreadsAlive = async (client: Client) => {
  try {
    if (!client.isReady() || client.guilds.cache.size === 0) return

    for (const guild of client.guilds.cache.values()) {
      const fetchedThreads = await guild.channels.fetchActiveThreads()

      for (const [_threadId, thread] of fetchedThreads.threads) {
        if (!thread.name.includes("💾")) continue
        const archiveAt = DateTime.fromMillis(thread.archiveTimestamp || 0)

        if (thread.archived) {
          const message = `🔍 Revived: ${thread.name} -- ${archiveAt.toFormat("F")}`
          await thread.send(message)
        }
      }
    }
  } catch (error) {
    console.error("Error scanning and reviving threads:", error)
  } finally {
    setTimeout(() => keepThreadsAlive(client), timeout)
  }
}
