const express = require('express');
const router = express.Router();
const authController = require('../controllers/authController');
const { protect } = require('../middlewares/auth');

router.post('/login', authController.login);
router.post('/change-password', protect, authController.changePassword);
router.get('/me', protect, authController.getMe);

// Password Reset Routes
const resetRateLimit = new Map();
const rateLimitMiddleware = (req, res, next) => {
    const identity = req.body.identity;
    if (!identity) return next();
    const now = Date.now();
    const lastRequest = resetRateLimit.get(identity);
    if (lastRequest && (now - lastRequest < 60000)) { // 1 min limit per identity
        return res.status(429).json({ message: 'Too many requests. Please wait a minute.' });
    }
    resetRateLimit.set(identity, now);
    next();
};

router.post('/request-reset', rateLimitMiddleware, authController.requestReset);
router.post('/verify-reset', authController.verifyReset);

module.exports = router;
