import { Router } from 'express'; import type { WebContext } from '../context.js'; export function createConfigRouter(ctx: WebContext): Router { const router = Router(); router.get('/config', (_req, res) => { res.json({ rateLimit: ctx.runtimeConfig.rateLimit, browser: { dryRun: ctx.runtimeConfig.browser.dryRun }, reddit: ctx.runtimeConfig.reddit, }); }); router.put('/config', (req, res) => { try { const updates = req.body; if (updates.rateLimit) { if (typeof updates.rateLimit.minDelayBetweenMessagesMs === 'number') { ctx.runtimeConfig.rateLimit.minDelayBetweenMessagesMs = Math.max( 0, updates.rateLimit.minDelayBetweenMessagesMs, ); } if (typeof updates.rateLimit.maxMessagesPerHour === 'number') { ctx.runtimeConfig.rateLimit.maxMessagesPerHour = Math.max( 1, updates.rateLimit.maxMessagesPerHour, ); } if (typeof updates.rateLimit.jitterMs === 'number') { ctx.runtimeConfig.rateLimit.jitterMs = Math.max(0, updates.rateLimit.jitterMs); } } if (updates.browser) { if (typeof updates.browser.dryRun === 'boolean') { ctx.runtimeConfig.browser.dryRun = updates.browser.dryRun; } } if (updates.reddit) { if (typeof updates.reddit.prioritizeRecentPosts === 'boolean') { ctx.runtimeConfig.reddit.prioritizeRecentPosts = updates.reddit.prioritizeRecentPosts; } if (typeof updates.reddit.recentWindowMinutes === 'number' && updates.reddit.recentWindowMinutes > 0) { ctx.runtimeConfig.reddit.recentWindowMinutes = updates.reddit.recentWindowMinutes; } } // Mirror into the loaded config so getStats reflects new values. ctx.config.rateLimit.minDelayBetweenMessagesMs = ctx.runtimeConfig.rateLimit.minDelayBetweenMessagesMs; ctx.config.rateLimit.maxMessagesPerHour = ctx.runtimeConfig.rateLimit.maxMessagesPerHour; ctx.config.rateLimit.jitterMs = ctx.runtimeConfig.rateLimit.jitterMs; ctx.config.browser.dryRun = ctx.runtimeConfig.browser.dryRun; ctx.config.reddit.prioritizeRecentPosts = ctx.runtimeConfig.reddit.prioritizeRecentPosts; ctx.config.reddit.recentWindowMinutes = ctx.runtimeConfig.reddit.recentWindowMinutes; ctx.getOnConfigChange()?.(ctx.runtimeConfig); ctx.activity.push('info', 'Config updated via dashboard'); ctx.broadcaster.push('info', 'Configuration updated via dashboard', updates); res.json({ success: true, config: ctx.runtimeConfig }); } catch (error) { ctx.logger.error('Failed to update config:', error); res.status(400).json({ error: String(error) }); } }); return router; }