import { userPreferencesService } from '@/services/core/user-preferences';
import { TfsService } from './tfs';
import { addMinutes, getToday } from '@/lib/date-utils';
import { prisma } from '@/services/core/database';

export interface TfsSchedulerConfig {
  enabled: boolean;
  interval: 'hourly' | 'daily' | 'weekly';
}

export class TfsScheduler {
  private timer: NodeJS.Timeout | null = null;
  private isRunning = false;
  private currentUserId: string | null = null;

  /**
   * Démarre le planificateur de synchronisation TFS automatique
   */
  async start(userId?: string): Promise<void> {
    if (this.isRunning) {
      console.log('⚠️ TFS scheduler is already running');
      return;
    }

    const targetUserId = userId || 'default';
    const config = await this.getConfig(targetUserId);

    if (!config.enabled) {
      console.log('📋 Automatic TFS sync is disabled');
      return;
    }

    // Vérifier que TFS est configuré
    const tfsConfig = await userPreferencesService.getTfsConfig(targetUserId);
    if (
      !tfsConfig.enabled ||
      !tfsConfig.organizationUrl ||
      !tfsConfig.personalAccessToken
    ) {
      console.log('⚠️ TFS not configured, scheduler cannot start');
      return;
    }

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

    // Première synchronisation immédiate (optionnelle)
    // this.performScheduledSync();

    // Planifier les synchronisations suivantes
    this.timer = setInterval(() => {
      this.performScheduledSync(targetUserId);
    }, intervalMs);

    this.isRunning = true;
    this.currentUserId = targetUserId;
    console.log(
      `✅ TFS scheduler started with ${config.interval} interval for user ${targetUserId}`
    );
  }

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

    this.isRunning = false;
    this.currentUserId = null;
    console.log('🛑 TFS scheduler stopped');
  }

  /**
   * Redémarre le planificateur (utile lors des changements de config)
   */
  async restart(userId?: string): Promise<void> {
    this.stop();
    await this.start(userId);
  }

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

  /**
   * Effectue une synchronisation planifiée
   */
  private async performScheduledSync(
    userId: string = 'default'
  ): Promise<void> {
    try {
      console.log('🔄 Starting scheduled TFS sync...');

      // Récupérer la config TFS
      const tfsConfig = await userPreferencesService.getTfsConfig(userId);

      if (
        !tfsConfig.enabled ||
        !tfsConfig.organizationUrl ||
        !tfsConfig.personalAccessToken
      ) {
        console.log('⚠️ TFS config incomplete, skipping scheduled sync');
        return;
      }

      // Créer le service TFS
      const tfsService = new TfsService({
        enabled: tfsConfig.enabled,
        organizationUrl: tfsConfig.organizationUrl,
        projectName: tfsConfig.projectName,
        personalAccessToken: tfsConfig.personalAccessToken,
        repositories: tfsConfig.repositories || [],
        ignoredRepositories: tfsConfig.ignoredRepositories || [],
      });

      // Tester la connexion d'abord
      const connectionOk = await tfsService.testConnection();
      if (!connectionOk) {
        console.error('❌ Scheduled TFS sync failed: connection error');
        return;
      }

      // Récupérer le premier utilisateur pour la synchronisation automatique
      const firstUser = await prisma.user.findFirst({
        orderBy: { createdAt: 'asc' },
      });

      if (!firstUser) {
        console.error('❌ Scheduled TFS sync failed: no user found');
        return;
      }

      // Effectuer la synchronisation
      const result = await tfsService.syncTasks(firstUser.id);

      if (result.success) {
        console.log(
          `✅ Scheduled TFS sync completed: ${result.pullRequestsCreated} created, ${result.pullRequestsUpdated} updated, ${result.pullRequestsSkipped} skipped`
        );
      } else {
        console.error(
          `❌ Scheduled TFS sync failed: ${result.errors.join(', ')}`
        );
      }
    } catch (error) {
      console.error('❌ Scheduled TFS sync error:', error);
    }
  }

  /**
   * Convertit l'intervalle en millisecondes
   */
  private getIntervalMs(interval: TfsSchedulerConfig['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 synchronisation
   */
  async getNextSyncTime(): Promise<Date | null> {
    if (!this.isRunning || !this.timer) {
      return null;
    }

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

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

  /**
   * Récupère la configuration du scheduler depuis les user preferences
   */
  private async getConfig(
    userId: string = 'default'
  ): Promise<TfsSchedulerConfig> {
    try {
      const [tfsConfig, schedulerConfig] = await Promise.all([
        userPreferencesService.getTfsConfig(userId),
        userPreferencesService.getTfsSchedulerConfig(userId),
      ]);

      return {
        enabled:
          schedulerConfig.tfsAutoSync &&
          tfsConfig.enabled &&
          !!tfsConfig.organizationUrl &&
          !!tfsConfig.personalAccessToken,
        interval: schedulerConfig.tfsSyncInterval,
      };
    } catch (error) {
      console.error('Error getting TFS scheduler config:', error);
      return {
        enabled: false,
        interval: 'daily',
      };
    }
  }

  /**
   * Obtient les stats du planificateur
   */
  async getStatus(userId?: string) {
    const targetUserId = userId || 'default';
    const config = await this.getConfig(targetUserId);
    const tfsConfig = await userPreferencesService.getTfsConfig(targetUserId);

    return {
      isRunning: this.isRunning,
      isEnabled: config.enabled,
      interval: config.interval,
      nextSync: await this.getNextSyncTime(),
      tfsConfigured: !!(
        tfsConfig.organizationUrl && tfsConfig.personalAccessToken
      ),
    };
  }
}

// Instance singleton
export const tfsScheduler = new TfsScheduler();

// Auto-start du scheduler
// Démarrer avec un délai pour laisser l'app s'initialiser
setTimeout(() => {
  console.log('🚀 Auto-starting TFS scheduler...');
  tfsScheduler.start();
}, 8000); // 8 secondes, après le Jira scheduler
