const express = require('express');
const { verifyToken } = require('../middlewares/auth');
const { registrarAuditoria } = require('../middlewares/auditoria');

// Función para crear rutas CRUD básicas
const createCrudRoutes = (controller, modelName, options = {}) => {
  const router = express.Router();
  const { requireAuth = true, enableAudit = true } = options;

  // Middleware de autenticación si es requerido
  if (requireAuth) {
    router.use(verifyToken);
  }

  /**
   * @swagger
   * tags:
   *   name: ${modelName}
   *   description: Gestión de ${modelName}
   */

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}:
   *   get:
   *     summary: Obtener todos los registros
   *     tags: [${modelName}]
   *     parameters:
   *       - in: query
   *         name: page
   *         schema:
   *           type: integer
   *         description: Número de página
   *       - in: query
   *         name: limit
   *         schema:
   *           type: integer
   *         description: Registros por página
   *       - in: query
   *         name: search
   *         schema:
   *           type: string
   *         description: Término de búsqueda
   *       - in: query
   *         name: sortBy
   *         schema:
   *           type: string
   *         description: Campo para ordenar
   *       - in: query
   *         name: sortOrder
   *         schema:
   *           type: string
   *           enum: [ASC, DESC]
   *         description: Orden ascendente o descendente
   *     responses:
   *       200:
   *         description: Lista de registros
   *         content:
   *           application/json:
   *             schema:
   *               $ref: '#/components/schemas/Pagination'
   */
  router.get('/', controller.getAll);

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}/search:
   *   get:
   *     summary: Buscar registros
   *     tags: [${modelName}]
   *     parameters:
   *       - in: query
   *         name: q
   *         required: true
   *         schema:
   *           type: string
   *         description: Término de búsqueda
   *     responses:
   *       200:
   *         description: Resultados de búsqueda
   */
  router.get('/search', controller.search);

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}/{id}:
   *   get:
   *     summary: Obtener registro por ID
   *     tags: [${modelName}]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: ID del registro
   *     responses:
   *       200:
   *         description: Registro encontrado
   *       404:
   *         description: Registro no encontrado
   */
  router.get('/:id', controller.getById);

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}:
   *   post:
   *     summary: Crear nuevo registro
   *     tags: [${modelName}]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *     responses:
   *       201:
   *         description: Registro creado exitosamente
   */
  router.post(
    '/',
    enableAudit ? registrarAuditoria('CREATE', modelName) : (req, res, next) => next(),
    controller.create
  );

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}/{id}:
   *   put:
   *     summary: Actualizar registro
   *     tags: [${modelName}]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *     responses:
   *       200:
   *         description: Registro actualizado exitosamente
   */
  router.put(
    '/:id',
    enableAudit ? registrarAuditoria('UPDATE', modelName) : (req, res, next) => next(),
    controller.update
  );

  /**
   * @swagger
   * /api/${modelName.toLowerCase()}/{id}:
   *   delete:
   *     summary: Eliminar registro
   *     tags: [${modelName}]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *     responses:
   *       200:
   *         description: Registro eliminado exitosamente
   */
  router.delete(
    '/:id',
    enableAudit ? registrarAuditoria('DELETE', modelName) : (req, res, next) => next(),
    controller.delete
  );

  return router;
};

module.exports = { createCrudRoutes };