import cron from 'node-cron';
import { Subscription } from '../controllers/subscription/index.controller.js';

export class SubscriptionScheduler {
  private static isRunning = false;
  private static task: any = null;

  // Start the subscription checker (runs every hour)
  public static start() {
    if (this.isRunning) {
      console.log('Subscription scheduler is already running');
      return;
    }

    // Run every hour at minute 0
    this.task = (cron as any).schedule('0 * * * *', () => {
      this.runSubscriptionCheck();
    });

    this.isRunning = true;
    console.log(
      'Subscription scheduler started - will check for expired subscriptions every hour'
    );
  }

  // Run the subscription check
  private static async runSubscriptionCheck() {
    console.log('Running subscription expiration check...');
    try {
      // Create a mock request/response for the controller
      const mockReq = {} as any;
      const mockRes = {
        status: (code: number) => ({
          json: (data: any) => {
            console.log(`Subscription check completed with status ${code}:`, data);
            return data;
          },
        }),
      } as any;
      const mockNext = () => {};

      await Subscription.checkExpiredSubscriptions(mockReq, mockRes, mockNext);
    } catch (error) {
      console.error('Error in scheduled subscription check:', error);
    }
  }

  // Stop the scheduler
  public static stop() {
    if (this.task) {
      this.task.stop();
      this.task = null;
    }
    this.isRunning = false;
    console.log('Subscription scheduler stopped');
  }

  // Manual check (can be called from API or admin panel)
  public static async manualCheck() {
    return await this.runSubscriptionCheck();
  }
}
