/**
 * Next.js Instrumentation Hook
 *
 * Wird beim Server-Start ausgeführt. Initialisiert Scheduled Jobs.
 * https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
 */
export async function register() {
  // Nur auf dem Server ausführen, nicht im Edge Runtime
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { getPayload } = await import('payload')
    const config = await import('./payload.config')

    // Payload initialisieren
    const payload = await getPayload({
      config: config.default,
    })

    const schedulerMode = (
      process.env.SCHEDULER_MODE ||
      (process.env.NODE_ENV === 'production' ? 'external' : 'in-process')
    ).toLowerCase()
    const explicitInProcess = process.env.ENABLE_IN_PROCESS_SCHEDULER === 'true'
    const shouldRunInProcessScheduler =
      schedulerMode === 'in-process' ||
      (explicitInProcess && schedulerMode !== 'external')

    if (process.env.NODE_ENV === 'production' && shouldRunInProcessScheduler) {
      console.warn(
        '[Instrumentation] In-process scheduler is enabled in production. ' +
        'Use SCHEDULER_MODE=external for multi-instance safe scheduling.',
      )
    }

    if (shouldRunInProcessScheduler) {
      const { initScheduledJobs } = await import('./jobs/scheduler')
      initScheduledJobs(payload)
    } else {
      console.log(
        '[Instrumentation] In-process scheduler disabled (SCHEDULER_MODE=external).',
      )
    }

    console.log('[Instrumentation] Payload und Scheduled Jobs initialisiert.')
  }
}
