import { getStringSetting } from '../models/settingsModel.js';
import { syncDynamicHostGroups } from '../models/hostGroupModel.js';
import { logger } from './logger.js';

let timer = null;
let running = false;

export function hostGroupSyncIntervalMinutes() {
  const minutes = Number(getStringSetting('host_group_sync_interval_minutes', process.env.HOST_GROUP_SYNC_INTERVAL_MINUTES || '60'));
  return Number.isFinite(minutes) ? minutes : 60;
}

export function startHostGroupWorker() {
  const minutes = hostGroupSyncIntervalMinutes();
  if (minutes <= 0) return null;
  running = true;
  scheduleNext(minutes);
  logger.info(`host group sync scheduled every ${minutes} minute(s)`);
  return timer;
}

export function stopHostGroupWorker() {
  running = false;
  if (timer) clearTimeout(timer);
  timer = null;
}

function scheduleNext(minutes) {
  if (!running || minutes <= 0) return;
  timer = setTimeout(() => {
    try {
      const summary = syncDynamicHostGroups();
      logger.info('host group sync complete', summary);
    } catch (error) {
      logger.error('host group sync failed', { error: error.message });
    } finally {
      scheduleNext(hostGroupSyncIntervalMinutes());
    }
  }, minutes * 60 * 1000);
  timer.unref?.();
}
