// server/plugins/check-slack-joins.js
import { checkSlackJoins } from '../utils/checkSlackJoins.js'

const INTERVAL_MS = 3600000 // 1 hour

export default defineNitroPlugin(() => {
  // Don't run in test environment
  if (process.env.NODE_ENV === 'test') return

  const config = useRuntimeConfig()
  const token = config.slackBotToken

  if (!token) {
    console.warn('[check-slack-joins] No Slack bot token configured, skipping background job')
    return
  }

  async function run() {
    try {
      await checkSlackJoins(token)
    } catch (err) {
      console.error('[check-slack-joins] Unhandled error:', err.message || err)
    }
  }

  // Run immediately on server start, then every hour
  run()
  setInterval(run, INTERVAL_MS)
})
