import { backupService, BackupConfig } from './backup';
import { addMinutes, getToday } from '@/lib/date-utils';

export class BackupScheduler {
  private timer: NodeJS.Timeout | null = null;
  private isRunning = false;

  /**
   * Démarre le planificateur de sauvegarde automatique
   */
  start(): void {
    if (this.isRunning) {
      console.log('⚠️ Backup scheduler is already running');
      return;
    }

    const config = backupService.getConfigSync();

    if (!config.enabled) {
      console.log('📋 Automatic backups are disabled');
      return;
    }

    const intervalMs = this.getIntervalMs(config.interval);

    // Première sauvegarde immédiate (optionnelle)
    // this.performScheduledBackup();

    // Planifier les sauvegardes suivantes
    this.timer = setInterval(() => {
      this.performScheduledBackup();
    }, intervalMs);

    this.isRunning = true;
    console.log(`✅ Backup scheduler started with ${config.interval} interval`);
  }

  /**
   * Arrête le planificateur
   */
  stop(): void {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    this.isRunning = false;
    console.log('🛑 Backup scheduler stopped');
  }

  /**
   * Redémarre le planificateur (utile lors des changements de config)
   */
  restart(): void {
    this.stop();
    this.start();
  }

  /**
   * Vérifie si le planificateur fonctionne
   */
  isActive(): boolean {
    return this.isRunning && this.timer !== null;
  }

  /**
   * Effectue une sauvegarde planifiée
   */
  private async performScheduledBackup(): Promise<void> {
    try {
      console.log('🔄 Starting scheduled backup...');
      const result = await backupService.createBackup('automatic');

      if (result === null) {
        console.log('⏭️ Scheduled backup skipped: no changes detected');
      } else if (result.status === 'success') {
        console.log(`✅ Scheduled backup completed: ${result.filename}`);
      } else {
        console.error(`❌ Scheduled backup failed: ${result.error}`);
      }
    } catch (error) {
      console.error('❌ Scheduled backup error:', error);
    }
  }

  /**
   * Convertit l'intervalle en millisecondes
   */
  private getIntervalMs(interval: BackupConfig['interval']): number {
    const intervals = {
      hourly: 60 * 60 * 1000, // 1 heure
      daily: 24 * 60 * 60 * 1000, // 24 heures
      weekly: 7 * 24 * 60 * 60 * 1000, // 7 jours
    };

    return intervals[interval];
  }

  /**
   * Obtient le prochain moment de sauvegarde
   */
  getNextBackupTime(): Date | null {
    if (!this.isRunning || !this.timer) {
      return null;
    }

    const config = backupService.getConfigSync();
    const intervalMs = this.getIntervalMs(config.interval);

    return addMinutes(getToday(), Math.floor(intervalMs / (1000 * 60)));
  }

  /**
   * Obtient les stats du planificateur
   */
  getStatus() {
    const config = backupService.getConfigSync();

    return {
      isRunning: this.isRunning,
      isEnabled: config.enabled,
      interval: config.interval,
      nextBackup: this.getNextBackupTime(),
      maxBackups: config.maxBackups,
      backupPath: config.backupPath,
    };
  }
}

// Instance singleton
export const backupScheduler = new BackupScheduler();

// Auto-start du scheduler
// Démarrer avec un délai pour laisser l'app s'initialiser
setTimeout(() => {
  console.log('🚀 Auto-starting backup scheduler...');
  backupScheduler.start();
}, 5000); // 5 secondes en dev, pour faciliter les tests
