import { Router } from 'express';
import candidatesRouter from './candidates.js';

const router = Router();

// GET /api/slides/:id
router.get('/:id', async (req, res) => {
  const pool = req.app.get('pool');
  const { id } = req.params;
  try {
    const result = await pool.query('SELECT * FROM slides WHERE id = $1', [id]);
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Slide not found' });
    }
    res.json({ slide: result.rows[0] });
  } catch (err) {
    console.error('Get slide error:', err);
    res.status(500).json({ error: 'Failed to fetch slide' });
  }
});

// PUT /api/slides/:id — update timing, component_key, props, presenter_notes, display_mode
router.put('/:id', async (req, res) => {
  const pool = req.app.get('pool');
  const { id } = req.params;
  const { start_time_sec, end_time_sec, component_key, props, presenter_notes, display_mode } = req.body;
  try {
    const result = await pool.query(
      `UPDATE slides SET
        start_time_sec  = COALESCE($1, start_time_sec),
        end_time_sec    = COALESCE($2, end_time_sec),
        component_key   = COALESCE($3, component_key),
        props           = COALESCE($4, props),
        presenter_notes = COALESCE($5, presenter_notes),
        display_mode    = COALESCE($6, display_mode),
        updated_at      = NOW()
      WHERE id = $7 RETURNING *`,
      [start_time_sec, end_time_sec, component_key,
       props ? JSON.stringify(props) : null,
       presenter_notes, display_mode, id]
    );
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Slide not found' });
    }
    res.json({ slide: result.rows[0] });
  } catch (err) {
    console.error('Update slide error:', err);
    res.status(500).json({ error: 'Failed to update slide' });
  }
});

// DELETE /api/slides/:id
router.delete('/:id', async (req, res) => {
  const pool = req.app.get('pool');
  const { id } = req.params;
  try {
    const result = await pool.query('DELETE FROM slides WHERE id = $1 RETURNING id', [id]);
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Slide not found' });
    }
    res.json({ success: true });
  } catch (err) {
    console.error('Delete slide error:', err);
    res.status(500).json({ error: 'Failed to delete slide' });
  }
});

router.use('/:slideId/candidates', candidatesRouter);

export default router;
