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, selfAward,
  adminAward, adminReset, adminGamStats, adminGetUser
} = require('../controllers/gamificationController');
const { isGamificationEnabled } = require('../controllers/gamification/_shared');

/* When gamification is globally disabled, user-facing routes return 404.
   Admin routes (under /admin/*) stay accessible so the kill-switch itself
   can still be flipped from the panel. */
function gamGate(req, res, next) {
  if (req.path.startsWith('/admin/')) return next();
  if (!isGamificationEnabled()) {
    return res.status(404).json({ error: 'Gamification disabled' });
  }
  next();
}

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

const tbLimiter     = rateLimit({ windowMs: 60_000, max: 30, message: 'Слишком частые начисления XP' });
const selfAwardSchema = {
  body: {
    amount: { type: 'number', required: true, min: 1, max: 50, integer: true },
    source: { type: 'string', required: true, minLen: 1, maxLen: 60,
               match: /^[a-z0-9_-]{1,60}$/i },
  },
};

router.use(authMiddleware);
router.use(gamGate);

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);

/* Учебник — начисление XP от пользователя */
router.post('/self-award', tbLimiter, validate(selfAwardSchema), selfAward);

/* 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;
