const router = require('express').Router();
const { authMiddleware, requireRole } = require('../middleware/auth');
const { requireOwnership } = require('../middleware/ownership');
const ctrl = require('../controllers/testController');

const ownsTest = requireOwnership({ table: 'tests', ownerField: 'created_by' });

router.use(authMiddleware);

router.get('/',                          ctrl.list);
router.post('/',                         requireRole('teacher','admin'), ctrl.create);
router.get('/:id',                       ctrl.getOne);
router.put('/:id',                       requireRole('teacher','admin'), ownsTest, ctrl.update);
router.delete('/:id',                    requireRole('teacher','admin'), ownsTest, ctrl.remove);
router.post('/:id/questions',            requireRole('teacher','admin'), ownsTest, ctrl.addQuestions);
router.patch('/:id/questions/reorder',   requireRole('teacher','admin'), ownsTest, ctrl.reorderQuestions);
router.delete('/:id/questions/:qid',     requireRole('teacher','admin'), ownsTest, ctrl.removeQuestion);

module.exports = router;
