import cron from 'node-cron'
import type { Payload } from 'payload'
import { runConsentRetentionJob } from './consentRetentionJob'
import { runSyncAllCommentsJob } from './syncAllComments'

/**
 * Initialisiert alle Scheduled Jobs
 */
export const initScheduledJobs = (payload: Payload): void => {
  // Consent Retention: Täglich um 03:00 Uhr
  cron.schedule(
    '0 3 * * *',
    async () => {
      console.log('[Scheduler] Starte Consent Retention Job...')
      try {
        await runConsentRetentionJob(payload)
      } catch (error) {
        console.error('[Scheduler] Consent Retention Job fehlgeschlagen:', error)
      }
    },
    {
      timezone: 'Europe/Berlin',
    },
  )

  // Comment Sync: Alle 15 Minuten
  const syncInterval = process.env.COMMUNITY_SYNC_CRON || '*/15 * * * *'
  cron.schedule(
    syncInterval,
    async () => {
      console.log('[Scheduler] Starte Comment Sync Job...')
      try {
        await runSyncAllCommentsJob(payload)
      } catch (error) {
        console.error('[Scheduler] Comment Sync Job fehlgeschlagen:', error)
      }
    },
    {
      timezone: 'Europe/Berlin',
    },
  )

  console.log('[Scheduler] Scheduled Jobs initialisiert.')
  console.log(`  - Consent Retention: Täglich um 03:00`)
  console.log(`  - Comment Sync: ${syncInterval}`)
}
