// backend/src/jobs/scheduler.js
import cron from 'node-cron';
import { query } from '../utils/db.js';
import { enqueuePipeline } from './pipeline-worker.js';
import { logger } from '../utils/logger.js';

export function startScheduler() {
  // Every hour: check which users have scheduled runs due
  cron.schedule('0 * * * *', async () => {
    const currentHour = new Date().getHours();
    logger.info(`Scheduler tick: hour ${currentHour}`);

    try {
      // Get active users whose schedule matches current hour (simplified: run at 6 AM UTC)
      const { rows: users } = await query(
        `SELECT u.id FROM users u
         LEFT JOIN user_profiles up ON up.user_id = u.id
         WHERE u.status IN ('active', 'trial')
           AND u.role = 'client'
           AND EXTRACT(HOUR FROM NOW() AT TIME ZONE COALESCE(up.output_timezone, 'UTC')) = 6
           AND NOT EXISTS (
             SELECT 1 FROM pipeline_runs pr
             WHERE pr.user_id = u.id
               AND pr.triggered_by = 'schedule'
               AND DATE(pr.created_at AT TIME ZONE COALESCE(up.output_timezone, 'UTC')) = CURRENT_DATE
           )
        `
      );

      logger.info(`Scheduling ${users.length} pipeline runs`);

      for (const user of users) {
        try {
          await enqueuePipeline(user.id, 'schedule');
          logger.info(`Enqueued scheduled pipeline for user ${user.id}`);
        } catch (err) {
          logger.error(`Failed to enqueue pipeline for user ${user.id}`, err.message);
        }
      }
    } catch (err) {
      logger.error('Scheduler error', err);
    }
  });

  // Daily: mark expired trials
  cron.schedule('0 0 * * *', async () => {
    try {
      const { rowCount } = await query(
        "UPDATE users SET status = 'past_due' WHERE status = 'trial' AND trial_ends_at < NOW()"
      );
      if (rowCount > 0) logger.info(`Expired ${rowCount} trials`);
    } catch (err) {
      logger.error('Trial expiry job error', err);
    }
  });

  logger.info('Cron scheduler started');
}
