import { syncWikiArticles } from '../utils/syncWikiArticles.js'

const INTERVAL_MS = 86400000 // 24 hours

export default defineNitroPlugin(() => {
  if (process.env.NODE_ENV === 'test') return

  const config = useRuntimeConfig()
  if (!config.outlineApiKey) {
    console.warn('[wiki-sync] No Outline API key configured, skipping background sync')
    return
  }

  async function run() {
    try {
      const result = await syncWikiArticles()
      console.log(`[wiki-sync] Done: ${result.created} created, ${result.updated} updated, ${result.deleted} removed, ${result.errors} errors`)
    } catch (err) {
      console.error('[wiki-sync] Unhandled error:', err.message || err)
    }
  }

  // Run on server start, then every 24 hours
  run()
  setInterval(run, INTERVAL_MS)
})
