import { Router } from 'express';
import { body, validationResult } from 'express-validator';
import { login, getMe, logout, getAuthConfig } from '../controllers/auth.controller';
import { authenticate } from '../middleware/auth.middleware';
import { Request, Response, NextFunction } from 'express';

const router = Router();

// Validation middleware
const loginValidation = [
  body('email')
    .isEmail()
    .withMessage('Email không hợp lệ')
    .normalizeEmail(),
  body('password')
    .notEmpty()
    .withMessage('Mật khẩu là bắt buộc'),
];

// Handle validation errors middleware
const handleValidationErrors = (req: Request, res: Response, next: NextFunction): void => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.status(400).json({
      success: false,
      message: errors.array()[0].msg || 'Validation failed',
      errors: errors.array(),
    });
    return;
  }
  next();
};

router.get('/config', getAuthConfig);
router.post('/login', loginValidation, handleValidationErrors, login);
router.get('/me', authenticate, getMe);
router.post('/logout', authenticate, logout);

export default router;
