const express = require('express');
const router = express.Router();
// Controladores de autenticación
const { login, register, changePassword, changePasswordsintoken } = require('../controllers/auth.controller');
const { verifyToken } = require('../middlewares/auth');
const { validateLogin, validateRegister, validatePasswordChange, validateResetPassword } = require('../middlewares/validator');
const { authLimiter } = require('../middlewares/rateLimiter');
const { authLogger } = require('../middlewares/requestLogger');
// Controladores de reset de contraseña
const adminController = require('../controllers/admin.controller');
const doctorController = require('../controllers/doctor.controller');
const clienteController = require('../controllers/cliente.controller');

/**
 * @swagger
 * tags:
 *   name: Auth
 *   description: Autenticación y autorización
 */

/**
 * @swagger
 * /api/auth/admin/login:
 *   post:
 *     summary: Login de administrador
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - password
 *             properties:
 *               email:
 *                 type: string
 *                 format: email
 *               password:
 *                 type: string
 *                 format: password
 *     responses:
 *       200:
 *         description: Login exitoso
 *       401:
 *         description: Credenciales inválidas
 */
router.post('/admin/login', authLimiter, validateLogin, authLogger('Login Admin'), (req, res, next) => {
  req.userType = 'admin';
  login(req, res, next);
});

/**
 * @swagger
 * /api/auth/admin/register:
 *   post:
 *     summary: Registro de administrador
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - password
 *               - Name
 *             properties:
 *               email:
 *                 type: string
 *               password:
 *                 type: string
 *               Name:
 *                 type: string
 *     responses:
 *       201:
 *         description: Registro exitoso
 */
router.post('/admin/register', validateRegister, authLogger('Registro Admin'), (req, res, next) => {
  req.userType = 'admin';
  register(req, res, next);
});

/**
 * @swagger
 * /api/auth/doctor/login:
 *   post:
 *     summary: Login de doctor
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - password
 *             properties:
 *               email:
 *                 type: string
 *               password:
 *                 type: string
 *     responses:
 *       200:
 *         description: Login exitoso
 */
router.post('/doctor/login', authLimiter, validateLogin, authLogger('Login Doctor'), (req, res, next) => {
  req.userType = 'doctor';
  login(req, res, next);
});

/**
 * @swagger
 * /api/auth/doctor/register:
 *   post:
 *     summary: Registro de doctor
 *     tags: [Auth]
 */
router.post('/doctor/register', validateRegister, authLogger('Registro Doctor'), (req, res, next) => {
  req.userType = 'doctor';
  register(req, res, next);
});

/**
 * @swagger
 * /api/auth/cliente/login:
 *   post:
 *     summary: Login de cliente
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - password
 *             properties:
 *               email:
 *                 type: string
 *               password:
 *                 type: string
 *     responses:
 *       200:
 *         description: Login exitoso
 */
router.post('/cliente/login', authLimiter, validateLogin, authLogger('Login Cliente'), (req, res, next) => {
  req.userType = 'cliente';
  login(req, res, next);
});

/**
 * @swagger
 * /api/auth/cliente/register:
 *   post:
 *     summary: Registro de cliente
 *     tags: [Auth]
 */
router.post('/cliente/register', authLogger('Registro Cliente'), (req, res, next) => {
  req.userType = 'cliente';
  register(req, res, next);
});

/**
 * @swagger
 * /api/auth/change-password:
 *   post:
 *     summary: Cambiar contraseña (requiere autenticación)
 *     tags: [Auth]
 *     security:
 *       - bearerAuth: []
 */
router.post('/change-password', verifyToken, validatePasswordChange, authLogger('Cambio de Contraseña'), changePassword);
/**
 * @swagger
 * /api/auth/recover-password:
 *   post:
 *     summary: Cambiar contraseña
 *     tags: [Auth]
 *     security:
 *       - bearerAuth: []
 */
router.post('/recover-password', authLogger('Recuperar Contraseña'), changePasswordsintoken);

// ============================================
// RUTAS DE RESET DE CONTRASEÑA - ADMIN
// ============================================
/**
 * @swagger
 * /api/auth/admin/reset-password:
 *   post:
 *     summary: Resetear contraseña de admin usando teléfono
 *     tags: [Auth - Reset Password]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - phone
 *               - newPassword
 *             properties:
 *               phone:
 *                 type: string
 *                 description: Número de teléfono del administrador
 *                 example: "+573001234567"
 *               newPassword:
 *                 type: string
 *                 format: password
 *                 description: Nueva contraseña (mínimo 6 caracteres)
 *                 example: "newPassword123"
 *     responses:
 *       200:
 *         description: Contraseña reseteada exitosamente
 *       404:
 *         description: Administrador no encontrado
 *       400:
 *         description: Datos inválidos
 */
router.post(
  '/admin/reset-password', 
  authLimiter, 
  validateResetPassword, 
  authLogger('Reset Password Admin'),
  adminController.resetPasswordByPhone
);

/**
 * @swagger
 * /api/auth/admin/verify-phone/{phone}:
 *   get:
 *     summary: Verificar si existe un admin con ese teléfono
 *     tags: [Auth - Reset Password]
 */
router.get(
  '/admin/verify-phone/:phone',
  authLogger('Verificar Teléfono Admin'),
  adminController.verifyPhoneExists
);

/**
 * @swagger
 * /api/auth/admin/request-code:
 *   post:
 *     summary: Solicitar código de verificación para admin
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/admin/request-code',
  authLimiter,
  authLogger('Solicitar Código Admin'),
  adminController.requestVerificationCode
);

// ============================================
// RUTAS DE RESET DE CONTRASEÑA - DOCTOR
// ============================================

/**
 * @swagger
 * /api/auth/doctor/reset-password:
 *   post:
 *     summary: Resetear contraseña de doctor usando número de matrícula médica
 *     tags: [Auth - Reset Password]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - medicalSchoolNumber
 *               - newPassword
 *             properties:
 *               medicalSchoolNumber:
 *                 type: string
 *                 description: Número de matrícula médica del doctor
 *                 example: "MED123456"
 *               newPassword:
 *                 type: string
 *                 format: password
 *                 description: Nueva contraseña (mínimo 6 caracteres)
 *     responses:
 *       200:
 *         description: Contraseña reseteada exitosamente
 *       404:
 *         description: Doctor no encontrado
 */
router.post(
  '/doctor/reset-password',
  authLimiter,
  validateResetPassword,
  authLogger('Reset Password Doctor'),
  doctorController.resetPasswordByMedicalSchoolNumber
);

/**
 * @swagger
 * /api/auth/doctor/verify-medical-number/{medicalSchoolNumber}:
 *   get:
 *     summary: Verificar si existe un doctor con ese número de matrícula
 *     tags: [Auth - Reset Password]
 */
router.get(
  '/doctor/verify-medical-number/:medicalSchoolNumber',
  authLogger('Verificar Matrícula Doctor'),
  doctorController.verifyMedicalSchoolNumberExists
);

/**
 * @swagger
 * /api/auth/doctor/request-code:
 *   post:
 *     summary: Solicitar código de verificación para doctor
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/doctor/request-code',
  authLimiter,
  authLogger('Solicitar Código Doctor'),
  doctorController.requestVerificationCode
);

/**
 * @swagger
 * /api/auth/doctor/reset-password-with-code:
 *   post:
 *     summary: Resetear contraseña de doctor con código de verificación
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/doctor/reset-password-with-code',
  authLimiter,
  validateResetPassword,
  authLogger('Reset Password con Código Doctor'),
  doctorController.resetPasswordWithCode
);

// ============================================
// RUTAS DE RESET DE CONTRASEÑA - CLIENTE
// ============================================

/**
 * @swagger
 * /api/auth/cliente/reset-password:
 *   post:
 *     summary: Resetear contraseña de cliente usando número de documento
 *     tags: [Auth - Reset Password]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - documentNumber
 *               - newPassword
 *             properties:
 *               documentNumber:
 *                 type: string
 *                 description: Número de documento del paciente
 *                 example: "1234567890"
 *               newPassword:
 *                 type: string
 *                 format: password
 *                 description: Nueva contraseña (mínimo 6 caracteres)
 *     responses:
 *       200:
 *         description: Contraseña reseteada exitosamente
 *       404:
 *         description: Paciente no encontrado
 */
router.post(
  '/cliente/reset-password',
  authLimiter,
  validateResetPassword,
  authLogger('Reset Password Cliente'),
  clienteController.resetPasswordByDocumentNumber
);

/**
 * @swagger
 * /api/auth/cliente/verify-document/{documentNumber}:
 *   get:
 *     summary: Verificar si existe un cliente con ese número de documento
 *     tags: [Auth - Reset Password]
 */
router.get(
  '/cliente/verify-document/:documentNumber',
  authLogger('Verificar Documento Cliente'),
  clienteController.verifyDocumentNumberExists
);

/**
 * @swagger
 * /api/auth/cliente/request-code:
 *   post:
 *     summary: Solicitar código de verificación para cliente
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/cliente/request-code',
  authLimiter,
  authLogger('Solicitar Código Cliente'),
  clienteController.requestVerificationCode
);

/**
 * @swagger
 * /api/auth/cliente/reset-password-with-code:
 *   post:
 *     summary: Resetear contraseña de cliente con código de verificación
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/cliente/reset-password-with-code',
  authLimiter,
  validateResetPassword,
  authLogger('Reset Password con Código Cliente'),
  clienteController.resetPasswordWithCode
);

/**
 * @swagger
 * /api/auth/cliente/verify-and-send-code:
 *   post:
 *     summary: Verificar documento y enviar código en un solo paso
 *     tags: [Auth - Reset Password]
 */
router.post(
  '/cliente/verify-and-send-code',
  authLimiter,
  authLogger('Verificar y Enviar Código Cliente'),
  clienteController.verifyAndSendCode
);

module.exports = router;