"use strict";
/**
 * CapacitacionController - Controller de capacitaciones HSE
 *
 * Endpoints REST para gestión de catálogo de capacitaciones.
 *
 * @module HSE
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCapacitacionController = createCapacitacionController;
const express_1 = require("express");
const capacitacion_service_1 = require("../services/capacitacion.service");
const auth_middleware_1 = require("../../auth/middleware/auth.middleware");
const auth_service_1 = require("../../auth/services/auth.service");
const capacitacion_entity_1 = require("../entities/capacitacion.entity");
const user_entity_1 = require("../../core/entities/user.entity");
const tenant_entity_1 = require("../../core/entities/tenant.entity");
const refresh_token_entity_1 = require("../../auth/entities/refresh-token.entity");
/**
 * Crear router de capacitaciones
 */
function createCapacitacionController(dataSource) {
    const router = (0, express_1.Router)();
    // Repositorios
    const capacitacionRepository = dataSource.getRepository(capacitacion_entity_1.Capacitacion);
    const userRepository = dataSource.getRepository(user_entity_1.User);
    const tenantRepository = dataSource.getRepository(tenant_entity_1.Tenant);
    const refreshTokenRepository = dataSource.getRepository(refresh_token_entity_1.RefreshToken);
    // Servicios
    const capacitacionService = new capacitacion_service_1.CapacitacionService(capacitacionRepository);
    const authService = new auth_service_1.AuthService(userRepository, tenantRepository, refreshTokenRepository);
    const authMiddleware = new auth_middleware_1.AuthMiddleware(authService, dataSource);
    // Helper para crear contexto de servicio
    const getContext = (req) => {
        if (!req.tenantId) {
            throw new Error('Tenant ID is required');
        }
        return {
            tenantId: req.tenantId,
            userId: req.user?.sub,
        };
    };
    /**
     * GET /capacitaciones
     * Listar capacitaciones con filtros
     */
    router.get('/', authMiddleware.authenticate, async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const page = parseInt(req.query.page) || 1;
            const limit = Math.min(parseInt(req.query.limit) || 20, 100);
            const filters = {
                tipo: req.query.tipo,
                activo: req.query.activo === 'true' ? true : req.query.activo === 'false' ? false : undefined,
                search: req.query.search,
            };
            const result = await capacitacionService.findAll(getContext(req), filters, page, limit);
            res.status(200).json({
                success: true,
                data: result.data,
                pagination: result.meta,
            });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /capacitaciones/by-tipo/:tipo
     * Obtener capacitaciones activas por tipo
     */
    router.get('/by-tipo/:tipo', authMiddleware.authenticate, async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const validTipos = ['induccion', 'especifica', 'certificacion', 'reentrenamiento'];
            if (!validTipos.includes(req.params.tipo)) {
                res.status(400).json({ error: 'Bad Request', message: 'Invalid tipo' });
                return;
            }
            const capacitaciones = await capacitacionService.getByTipo(getContext(req), req.params.tipo);
            res.status(200).json({ success: true, data: capacitaciones });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /capacitaciones/:id
     * Obtener capacitación por ID
     */
    router.get('/:id', authMiddleware.authenticate, async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const capacitacion = await capacitacionService.findById(getContext(req), req.params.id);
            if (!capacitacion) {
                res.status(404).json({ error: 'Not Found', message: 'Training not found' });
                return;
            }
            res.status(200).json({ success: true, data: capacitacion });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * POST /capacitaciones
     * Crear capacitación
     */
    router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const dto = req.body;
            if (!dto.codigo || !dto.nombre || !dto.tipo) {
                res.status(400).json({ error: 'Bad Request', message: 'codigo, nombre and tipo are required' });
                return;
            }
            const capacitacion = await capacitacionService.create(getContext(req), dto);
            res.status(201).json({ success: true, data: capacitacion });
        }
        catch (error) {
            if (error instanceof Error && error.message.includes('already exists')) {
                res.status(409).json({ error: 'Conflict', message: error.message });
                return;
            }
            next(error);
        }
    });
    /**
     * PATCH /capacitaciones/:id
     * Actualizar capacitación
     */
    router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const dto = req.body;
            const capacitacion = await capacitacionService.update(getContext(req), req.params.id, dto);
            if (!capacitacion) {
                res.status(404).json({ error: 'Not Found', message: 'Training not found' });
                return;
            }
            res.status(200).json({ success: true, data: capacitacion });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * POST /capacitaciones/:id/toggle-active
     * Activar/desactivar capacitación
     */
    router.post('/:id/toggle-active', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const capacitacion = await capacitacionService.toggleActive(getContext(req), req.params.id);
            if (!capacitacion) {
                res.status(404).json({ error: 'Not Found', message: 'Training not found' });
                return;
            }
            res.status(200).json({
                success: true,
                data: capacitacion,
                message: capacitacion.activo ? 'Training activated' : 'Training deactivated',
            });
        }
        catch (error) {
            next(error);
        }
    });
    return router;
}
exports.default = createCapacitacionController;
//# sourceMappingURL=capacitacion.controller.js.map