import { Router } from "express";
import { body } from "express-validator";

import { authController } from "../controllers/authController.js";
import { authenticateToken } from "../middleware/auth.js";
import { authLoginRateLimit } from "../middleware/rateLimit.js";
import { handleValidation } from "../middleware/validation.js";
import { asyncHandler } from "../utils/asyncHandler.js";

const router = Router();

router.post(
  "/login",
  authLoginRateLimit,
  [
    body("email").isEmail().withMessage("Adresse e-mail invalide."),
    body("password")
      .isLength({ min: 1 })
      .withMessage("Le mot de passe est obligatoire."),
    handleValidation,
  ],
  asyncHandler(authController.login),
);
router.post(
  "/mobile/login",
  authLoginRateLimit,
  [
    body("email").isEmail().withMessage("Adresse e-mail invalide."),
    body("password")
      .isLength({ min: 1 })
      .withMessage("Le mot de passe est obligatoire."),
    handleValidation,
  ],
  asyncHandler(authController.mobileLogin),
);
router.post(
  "/mobile/qr-login",
  authLoginRateLimit,
  [
    body("qr_token")
      .isLength({ min: 1 })
      .withMessage("Le QR token est obligatoire."),
    handleValidation,
  ],
  asyncHandler(authController.mobileQrLogin),
);
router.post("/logout", asyncHandler(authController.logout));
router.post("/refresh", asyncHandler(authController.refresh));
router.post(
  "/change-password",
  authenticateToken,
  [
    body("current_password")
      .isLength({ min: 1 })
      .withMessage("Le mot de passe actuel est obligatoire."),
    body("new_password")
      .isLength({ min: 8 })
      .withMessage("Le nouveau mot de passe doit contenir au moins 8 caractères."),
    handleValidation,
  ],
  asyncHandler(authController.changePassword),
);
router.post(
  "/set-module",
  authenticateToken,
  [
    body("module")
      .isIn(["SCF", "MGX", "TRACKING"])
      .withMessage("Module invalide."),
    handleValidation,
  ],
  asyncHandler(authController.setModule),
);
router.get("/me", authenticateToken, asyncHandler(authController.me));
router.get("/mobile/me", authenticateToken, asyncHandler(authController.mobileMe));

export default router;
