const express = require('express');
const router = express.Router();
const db = require('../db');

router.use((req, res, next) => {
  if (!req.session.user_id) return res.status(401).json({ error: 'Unauthorized' });
  next();
});

router.get('/', async (req, res) => {
  try {
    const rows = await db.query('SELECT action, details FROM activity_log ORDER BY created_at DESC');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/', async (req, res) => {
  try {
    await db.query('INSERT INTO activity_log (action, details) VALUES (?, ?)', [req.body.action, req.body.details || null]);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
