import cron from 'node-cron';
import autoUpdateRatingsService from './autoUpdateRatingsService.js';
import autoFetchMatchResultsService from './autoFetchMatchResultsService.js';
import apiLogService from './apiLogService.js';
import { devLog } from '../utils/logger.js';

class SchedulerService {
  constructor() {
    this.jobs = new Map();
    this.isRunning = false;
  }

  async runRatingUpdatesJob(isAutomatic = true) {
    const startTime = Date.now();
    try {
      const result = await autoUpdateRatingsService.executeAutomaticUpdates();
      const executionTime = Date.now() - startTime;
      await apiLogService.logSchedulerExecution('rating_updates', true, result || { success: true }, executionTime, null);
      return { success: true, result, executionTime, isAutomatic };
    } catch (error) {
      const executionTime = Date.now() - startTime;
      await apiLogService.logSchedulerExecution('rating_updates', false, { success: false }, executionTime, error?.message || String(error));
      return { success: false, error: error?.message || String(error), executionTime, isAutomatic };
    }
  }

  async runMatchResultsFetchJob(isAutomatic = true) {
    const startTime = Date.now();
    try {
      const result = await autoFetchMatchResultsService.executeAutomaticFetch();
      const executionTime = Date.now() - startTime;
      await apiLogService.logSchedulerExecution('match_results', true, result || { success: true }, executionTime, null);
      return { success: true, result, executionTime, isAutomatic };
    } catch (error) {
      const executionTime = Date.now() - startTime;
      await apiLogService.logSchedulerExecution('match_results', false, { success: false }, executionTime, error?.message || String(error));
      return { success: false, error: error?.message || String(error), executionTime, isAutomatic };
    }
  }

  /**
   * Start the scheduler
   */ 
  start() {
    if (this.isRunning) {
      devLog('Scheduler is already running');
      return;
    }
 
    devLog('Starting scheduler service...');

    // Rating Updates (6:00 AM)
    const ratingUpdateJob = cron.schedule('0 6 * * *', async () => {
      devLog('[Scheduler] Running rating updates job...');
      await this.runRatingUpdatesJob(true);
    }, {
      timezone: 'Europe/Berlin'
    });

    // Match Results Fetch (6:30 AM)
    const matchResultsJob = cron.schedule('30 6 * * *', async () => {
      devLog('[Scheduler] Running match results fetch job...');
      await this.runMatchResultsFetchJob(true);
    }, {
      timezone: 'Europe/Berlin'
    });

    this.jobs.set('ratingUpdates', ratingUpdateJob);
    this.jobs.set('matchResults', matchResultsJob);

    this.isRunning = true;
    const now = new Date();
    
    devLog('[Scheduler] ===== SCHEDULER SERVICE STARTED =====');
    devLog(`[Scheduler] Server time: ${now.toISOString()}`);
    devLog(`[Scheduler] Timezone: Europe/Berlin`);
  devLog(`[Scheduler] MyTischtennis automatic fetch jobs: ENABLED`);
    devLog('[Scheduler] =====================================');
    
    devLog('Scheduler service started successfully');
  devLog('MyTischtennis automatic fetch jobs are ENABLED');
  }

  /**
   * Stop the scheduler
   */
  stop() {
    if (!this.isRunning) {
      devLog('Scheduler is not running');
      return;
    }

    devLog('Stopping scheduler service...');

    for (const [name, job] of this.jobs) {
      job.stop();
      devLog(`Stopped job: ${name}`);
    }

    this.jobs.clear();
    this.isRunning = false;
    devLog('Scheduler service stopped');
  }

  /**
   * Get scheduler status
   */
  getStatus() {
    return {
      isRunning: this.isRunning,
      jobs: Array.from(this.jobs.keys()),
      timezone: 'Europe/Berlin'
    };
  }

  /**
   * Manually trigger rating updates (for testing)
   * HINWEIS: Deaktiviert - automatische MyTischtennis-Abrufe sind nicht mehr verfügbar
   */
  async triggerRatingUpdates() {
  devLog('[Scheduler] Manual rating updates trigger called');
  return await this.runRatingUpdatesJob(false);
  }

  /**
   * Manually trigger match results fetch (for testing)
   * HINWEIS: Deaktiviert - automatische MyTischtennis-Abrufe sind nicht mehr verfügbar
   */
  async triggerMatchResultsFetch() {
  devLog('[Scheduler] Manual match results fetch trigger called');
  return await this.runMatchResultsFetchJob(false);
  }

  /**
   * Get next scheduled execution time for rating updates
   */
  getNextRatingUpdateTime() {
    const job = this.jobs.get('ratingUpdates');
    if (!job || !this.isRunning) {
      return null;
    }

    // Get next execution time (this is a simplified approach)
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(6, 0, 0, 0);

    return tomorrow;
  }
}

export default new SchedulerService();
