const router = require('express').Router();
const { authMiddleware, requireRole, requirePermission } = require('../middleware/auth');
const validate  = require('../middleware/validate');
const rateLimit = require('../middleware/rateLimit');
const {
  getMe, getAchievements, getLeaderboard, getXPHistory,
  getChallenges, claimChallenge, setGoalTier, getFrames, setFrame,
  onLabExperiment,
  adminAward, adminReset, adminGamStats, adminGetUser
} = require('../controllers/gamificationController');

const labLimiter = rateLimit({ windowMs: 60_000, max: 30, message: 'Слишком частые запросы лаборатории' });
const labSchema  = { body: { reactionsDiscovered: { type: 'number', min: 0, max: 100, integer: true } } };

router.use(authMiddleware);

router.get('/me',              getMe);
router.get('/achievements',    getAchievements);
router.get('/leaderboard',     getLeaderboard);
router.get('/xp-history',      getXPHistory);
router.get('/challenges',      getChallenges);
router.post('/challenges/:id/claim', requirePermission('gamification.challenges'), claimChallenge);
router.post('/goal-tier', requirePermission('gamification.challenges'), setGoalTier);
router.get('/frames',    getFrames);
router.post('/frame',    requirePermission('shop.purchase'), setFrame);

/* Lab experiment tracking */
router.post('/lab-activity', requirePermission('simulations.access'), labLimiter, validate(labSchema), (req, res) => {
  const discovered = Number(req.body.reactionsDiscovered) || 0;
  onLabExperiment(req.user.id, discovered);
  res.json({ ok: true });
});

/* Admin routes — award/stats/user require gamification.manage permission
   (admin always passes; teachers need explicit grant from permissions UI) */
router.post('/admin/award',        requirePermission('gamification.manage'), adminAward);
router.post('/admin/reset',        requireRole('admin'),                     adminReset);
router.get('/admin/stats',         requirePermission('gamification.manage'), adminGamStats);
router.get('/admin/user/:id',      requirePermission('gamification.manage'), adminGetUser);

module.exports = router;
