// PRE Web GUI — Cron routes
const { Router } = require('express');
const cronSystem = require('../tools/cron');
const { executeCronJob } = require('../cron-runner');

// Factory: broadcastWS is needed for manual cron runs
module.exports = function createCronRoutes(broadcastWS) {
  const router = Router();

  router.get('/cron', (_req, res) => {
    res.json(cronSystem.loadJobs());
  });

  router.post('/cron', (req, res) => {
    const { schedule, prompt, description } = req.body || {};
    if (!schedule || !prompt) {
      return res.status(400).json({ error: 'schedule and prompt are required' });
    }
    const fields = schedule.trim().split(/\s+/);
    if (fields.length !== 5) {
      return res.status(400).json({ error: 'Schedule must be 5 fields: min hour dom month dow' });
    }
    const jobs = cronSystem.loadJobs();
    const job = {
      id: cronSystem.generateId(),
      schedule: schedule.trim(),
      prompt,
      description: description || prompt.slice(0, 80),
      enabled: true,
      created_at: Date.now(),
      last_run_at: null,
      run_count: 0,
    };
    jobs.push(job);
    cronSystem.saveJobs(jobs);
    res.json(job);
  });

  router.patch('/cron/:id', (req, res) => {
    const jobs = cronSystem.loadJobs();
    const job = jobs.find(j => j.id === req.params.id);
    if (!job) return res.status(404).json({ error: 'Job not found' });
    if (req.body.enabled !== undefined) job.enabled = !!req.body.enabled;
    if (req.body.schedule) job.schedule = req.body.schedule;
    if (req.body.prompt) job.prompt = req.body.prompt;
    if (req.body.description) job.description = req.body.description;
    cronSystem.saveJobs(jobs);
    res.json(job);
  });

  router.delete('/cron/:id', (req, res) => {
    const jobs = cronSystem.loadJobs();
    const idx = jobs.findIndex(j => j.id === req.params.id);
    if (idx === -1) return res.status(404).json({ error: 'Job not found' });
    const removed = jobs.splice(idx, 1)[0];
    cronSystem.saveJobs(jobs);
    res.json(removed);
  });

  router.post('/cron/:id/run', (req, res) => {
    const jobs = cronSystem.loadJobs();
    const job = jobs.find(j => j.id === req.params.id);
    if (!job) return res.status(404).json({ error: 'Job not found' });
    job.last_run_at = Date.now();
    job.run_count = (job.run_count || 0) + 1;
    cronSystem.saveJobs(jobs);
    executeCronJob(job, { broadcastWS }).catch(err => {
      console.error(`[cron] Manual run error for ${job.id}: ${err.message}`);
    });
    res.json({ ok: true, id: job.id, run_count: job.run_count });
  });

  return router;
};
