const memory = require('./memory.js'); // Scheduler memory

module.exports = async function() {
    try {
        const allTasks = memory.getAllTasks();

        // Stop all running timers without changing 'active' state
        for (const name in allTasks) {
            const task = allTasks[name];
            if (task.timer) {
                clearTimeout(task.timer);
                task.timer = null;
            }
        }

        // Build the return object with task status
        const tasksStatus = {};
        for (const name in allTasks) {
            const t = allTasks[name];
            tasksStatus[name] = {
                active: t.active,
                oneTime: t.oneTime,
                intervalInSec: t.intervalInSec,
                lastRun: t.lastRun,
                nextRun: t.nextRun,
                error: t.error,
                action: t.action
            };
        }

        return {
            online: false,  // service is stopped
            tasks: tasksStatus
        };
    } catch (err) {
        console.error('Failed to stop scheduler service:', err);
        return {
            online: false,
            tasks: {}
        };
    }
};