const express = require('express'); const router = express.Router(); const Cycle = require('../models/Cycle'); router.get('/', async (req, res) => { try { const cycles = await Cycle.getAll(); res.json({ success: true, data: cycles }); } catch (error) { console.error('Error in GET /api/cycles:', error); res.status(500).json({ success: false, error: error.message }); } }); router.get('/active', async (req, res) => { try { const cycle = await Cycle.getActive(); if (!cycle) return res.status(404).json({ success: false, error: 'No active cycle found' }); res.json({ success: true, data: cycle }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); router.get('/:id', async (req, res) => { try { const cycle = await Cycle.getById(req.params.id); if (!cycle) return res.status(404).json({ success: false, error: 'Cycle not found' }); res.json({ success: true, data: cycle }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); router.post('/', async (req, res) => { try { const { id, totalDays, currentDay, startDate, status } = req.body; if (!id || !totalDays || currentDay === undefined || !startDate || !status) { return res.status(400).json({ success: false, error: 'Missing required fields' }); } // CRITICAL: If creating a new "Active" cycle, automatically mark all previous "Active" cycles as "Completed" if (status === 'Active') { await Cycle.markAllActiveAsCompleted(); } const cycle = await Cycle.create(req.body); res.status(201).json({ success: true, data: cycle }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); router.put('/:id', async (req, res) => { try { const cycle = await Cycle.update(req.params.id, req.body); if (!cycle) return res.status(404).json({ success: false, error: 'Cycle not found' }); res.json({ success: true, data: cycle }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); router.delete('/:id', async (req, res) => { try { const deleted = await Cycle.delete(req.params.id); if (!deleted) return res.status(404).json({ success: false, error: 'Cycle not found' }); res.json({ success: true, message: 'Cycle deleted successfully' }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); module.exports = router;