import cron from 'node-cron';
import { logger } from '../../utils/logger.js';
import { sendEventNotifications, sendSingleEventNotification, sendOneHourBeforeNotifications } from './event-notifier.js';

/**
 * Parse NOTIFICATION_TIME from env (format: "HH:mm")
 * @returns {{ hour: string, minute: string }}
 */
const parseNotificationTime = () => {
  const time = process.env.NOTIFICATION_TIME || '07:00';
  const [hour, minute] = time.split(':');

  return {
    hour: hour || '7',
    minute: minute || '0',
  };
};

/**
 * Check if test mode is enabled
 * @returns {boolean}
 */
const isTestMode = () => {
  return process.env.NOTIFICATION_TEST_MODE === 'true';
};

/**
 * Start the calendar notification cron job
 * @returns {{ name: string, schedule: string }}
 */
export const startCalendarNotificationCron = () => {
  let cronExpression;
  let schedule;

  if (isTestMode()) {
    cronExpression = '* * * * *';
    schedule = 'every minute (TEST)';
    logger.warn('NOTIFICATION_TEST_MODE enabled - notifications run every minute!');
  } else {
    const { hour, minute } = parseNotificationTime();
    cronExpression = `${minute} ${hour} * * *`;
    schedule = `${hour}:${minute.padStart(2, '0')}`;
  }

  cron.schedule(cronExpression, async () => {
    logger.info('Running calendar notifications...');
    try {
      const stats = await sendEventNotifications();
      logger.info(`Notifications done: sent=${stats.sent}, failed=${stats.failed}, skipped=${stats.skipped}`);
    } catch (error) {
      logger.error('Calendar notification cron failed', error);
    }
  }, {
    scheduled: true,
    timezone: 'Europe/Bratislava',
  });

  return { name: `Calendar (${schedule})`, schedule };
};

/**
 * Start the 1-hour-before notification cron job (runs every hour)
 * @returns {{ name: string, schedule: string }}
 */
export const startOneHourBeforeNotificationCron = () => {
  const cronExpression = '0 * * * *'; // Every hour at minute 0
  const schedule = 'every hour';

  cron.schedule(cronExpression, async () => {
    logger.info('Running 1-hour-before notifications...');
    try {
      const stats = await sendOneHourBeforeNotifications();
      logger.info(`1h notifications done: sent=${stats.sent}, failed=${stats.failed}, skipped=${stats.skipped}`);
    } catch (error) {
      logger.error('1-hour-before notification cron failed', error);
    }
  }, {
    scheduled: true,
    timezone: 'Europe/Bratislava',
  });

  return { name: `1h Before (${schedule})`, schedule };
};

/**
 * Start the 18:00 notification cron job (tomorrow's events at 18:00)
 * @returns {{ name: string, schedule: string }}
 */
export const startEveningNotificationCron = () => {
  const cronExpression = '0 18 * * *'; // Every day at 18:00
  const schedule = '18:00';

  cron.schedule(cronExpression, async () => {
    logger.info('Running evening notifications for tomorrow...');
    try {
      const stats = await sendEventNotifications();
      logger.info(`Evening notifications done: sent=${stats.sent}, failed=${stats.failed}, skipped=${stats.skipped}`);
    } catch (error) {
      logger.error('Evening notification cron failed', error);
    }
  }, {
    scheduled: true,
    timezone: 'Europe/Bratislava',
  });

  return { name: `Evening (${schedule})`, schedule };
};

/**
 * Manually trigger event notifications (for testing)
 */
export const triggerEventNotifications = async () => {
  logger.info('Manually triggering notifications...');
  return sendEventNotifications();
};

/**
 * Send notification for a single event
 * @param {string} eventId - Event ID
 * @param {string} adminUserId - Admin user ID (sender)
 */
export const triggerSingleEventNotification = async (eventId, adminUserId) => {
  logger.info(`Manually triggering notification for event ${eventId}`);
  return sendSingleEventNotification(eventId, adminUserId);
};
