import { Router, type IRouter } from 'express';
import rateLimit from 'express-rate-limit';
import * as authController from '../controllers/auth.controller.js';
import { authenticate } from '../middlewares/auth.middleware.js';
import { strictLimit } from '../middlewares/rate-limit.middleware.js';

const router: IRouter = Router();

// Rate limiting: 25 login attempts per 15 minutes per IP
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 25,
  message: { message: 'Demasiados intentos de login. Intenta de nuevo en 15 minutos.' },
  standardHeaders: true,
  legacyHeaders: false,
});

// Rate limiting: 3 registrations per hour per IP
const registerLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 3,
  message: { message: 'Demasiados registros. Intenta de nuevo en 1 hora.' },
  standardHeaders: true,
  legacyHeaders: false,
});

// Rate limiting: 20 refresh attempts per 15 minutes per IP
const refreshLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 20,
  message: { message: 'Demasiadas solicitudes. Intenta de nuevo más tarde.' },
  standardHeaders: true,
  legacyHeaders: false,
});

// Rate limiting: 3 password reset requests per hour per IP — evita spam + enumeration
const passwordResetRequestLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 3,
  message: { message: 'Demasiadas solicitudes de recuperación. Intenta de nuevo en 1 hora.' },
  standardHeaders: true,
  legacyHeaders: false,
});

// Rate limiting: 10 confirm attempts per hour per IP — prevenir brute-force del token
const passwordResetConfirmLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 10,
  message: { message: 'Demasiados intentos. Intenta de nuevo más tarde.' },
  standardHeaders: true,
  legacyHeaders: false,
});

router.post('/register', registerLimiter, authController.register);
router.post('/login', loginLimiter, authController.login);
router.post('/refresh', refreshLimiter, authController.refresh);
router.post('/logout', authenticate, authController.logout);
router.get('/me', authenticate, authController.me);
router.post('/password-reset/request', passwordResetRequestLimiter, authController.requestPasswordReset);
router.post('/password-reset/confirm', passwordResetConfirmLimiter, authController.confirmPasswordReset);
// 10/hora — prevenir brute-force del currentPassword
router.post('/password-change', authenticate, strictLimit, authController.changePassword);
router.post('/logout-all', authenticate, authController.logoutAll);
router.post('/switch-tenant', authenticate, authController.switchTenant);
// Auto-dismiss del onboarding (lo llama el frontend cuando el user completa
// los pasos requeridos). Idempotente — múltiples llamadas no rompen.
router.post('/onboarding/dismiss', authenticate, authController.dismissOnboarding);

export { router as authRoutes };
