import { BaseCommand } from '../BaseCommand.js';
import { ScheduleCliSupport } from '../commands/schedule/ScheduleCliSupport.js';
import { Env } from '../../config/env.js';
import { Logger } from '../../config/logger.js';
import { ErrorFactory } from '../../exceptions/ZintrustError.js';
import { SchedulerRuntime } from '../../scheduler/SchedulerRuntime.js';
const waitForSignal = async () => {
    if (typeof process === 'undefined' || typeof process.once !== 'function') {
        throw ErrorFactory.createGeneralError('schedule:start is only supported in Node.js runtimes');
    }
    return new Promise((resolve) => {
        process.once('SIGTERM', () => resolve('SIGTERM'));
        process.once('SIGINT', () => resolve('SIGINT'));
    });
};
const execute = async (_options) => {
    if (Env.getBool('SCHEDULES_ENABLED', false) === false) {
        Logger.info('Schedules are disabled (SCHEDULES_ENABLED=false); exiting');
        return;
    }
    await ScheduleCliSupport.registerAll();
    const registeredCount = SchedulerRuntime.list().length;
    Logger.info('Starting schedules daemon', { registeredCount });
    SchedulerRuntime.start();
    const signal = await waitForSignal();
    Logger.info('Stopping schedules daemon', { signal });
    const timeoutMs = Env.getInt('SCHEDULE_SHUTDOWN_TIMEOUT_MS', 30000);
    await SchedulerRuntime.stop(timeoutMs);
    Logger.info('Schedules daemon stopped');
};
export const ScheduleStartCommand = Object.freeze({
    create() {
        return BaseCommand.create({
            name: 'schedule:start',
            description: 'Start schedules and keep running until SIGINT/SIGTERM',
            execute,
        });
    },
});
export default ScheduleStartCommand;
