'use strict';

const logger = require('../../utils/logger');
const service = require('./arkhon-card.service');

let timer = null;
let running = false;

function startArkhonCardScheduler() {
  if (timer) return;
  const intervalMs = Math.max(Number(process.env.ARKHON_CARD_INTERVAL_MS || 60000), 15000);
  timer = setInterval(async () => {
    if (running) return;
    running = true;
    try {
      const config = await service.getConfig();
      if (config.auto_apply_enabled) {
        const result = await service.applyLimits({ actor: 'scheduler' });
        if (result.applied?.length) {
          logger.info({ event: 'arkhon_card_scheduler_applied', applied: result.applied.length });
        }
      }
    } catch (err) {
      logger.warn({ event: 'arkhon_card_scheduler_failed', error: err.message });
    } finally {
      running = false;
    }
  }, intervalMs);
  timer.unref?.();
  logger.info({ event: 'arkhon_card_scheduler_started', interval_ms: intervalMs });
}

function stopArkhonCardScheduler() {
  if (!timer) return;
  clearInterval(timer);
  timer = null;
}

module.exports = {
  startArkhonCardScheduler,
  stopArkhonCardScheduler,
};
