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

timeBomb("7-15-2025", "Get rid of all these console messages Corey!")

// const timeout = 1000 * 60 * 30 // 30 minutes
// const timeout = 1000 * 60 // 1 minute
const timeout = 3000 // 1 minute
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) {
        const archiveAt = DateTime.fromMillis(thread.archiveTimestamp || 0)
        const result = await thread.setArchived(
          false,
          "Revived by Spike - keeping important discussion alive"
        )

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