"use strict";
/**
 * UsersController - Controlador de usuarios
 *
 * Endpoints REST para CRUD de usuarios y asignación de roles.
 *
 * @module Users
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUsersController = createUsersController;
const express_1 = require("express");
const users_service_1 = require("../services/users.service");
const auth_middleware_1 = require("../../auth/middleware/auth.middleware");
const auth_service_1 = require("../../auth/services/auth.service");
const user_entity_1 = require("../../core/entities/user.entity");
const tenant_entity_1 = require("../../core/entities/tenant.entity");
const role_entity_1 = require("../../auth/entities/role.entity");
const user_role_entity_1 = require("../../auth/entities/user-role.entity");
const refresh_token_entity_1 = require("../../auth/entities/refresh-token.entity");
/**
 * Crear router de usuarios
 */
function createUsersController(dataSource) {
    const router = (0, express_1.Router)();
    // Repositorios
    const userRepository = dataSource.getRepository(user_entity_1.User);
    const tenantRepository = dataSource.getRepository(tenant_entity_1.Tenant);
    const roleRepository = dataSource.getRepository(role_entity_1.Role);
    const userRoleRepository = dataSource.getRepository(user_role_entity_1.UserRole);
    const refreshTokenRepository = dataSource.getRepository(refresh_token_entity_1.RefreshToken);
    // Servicios
    const usersService = new users_service_1.UsersService(userRepository, roleRepository, userRoleRepository);
    const authService = new auth_service_1.AuthService(userRepository, tenantRepository, refreshTokenRepository);
    const authMiddleware = new auth_middleware_1.AuthMiddleware(authService, dataSource);
    /**
     * GET /users
     * Listar usuarios del tenant
     */
    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 search = req.query.search;
            const isActive = req.query.isActive === 'true' ? true : req.query.isActive === 'false' ? false : undefined;
            const result = await usersService.findAll({ tenantId, page, limit, search, isActive });
            res.status(200).json({
                success: true,
                data: result.users,
                pagination: {
                    page,
                    limit,
                    total: result.total,
                    totalPages: Math.ceil(result.total / limit),
                },
            });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /users/roles
     * Listar roles disponibles
     */
    router.get('/roles', authMiddleware.authenticate, async (_req, res, next) => {
        try {
            const roles = await usersService.listRoles();
            res.status(200).json({ success: true, data: roles });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /users/:id
     * Obtener usuario 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 user = await usersService.findById(req.params.id, tenantId);
            if (!user) {
                res.status(404).json({ error: 'Not Found', message: 'User not found' });
                return;
            }
            const roles = await usersService.getUserRoles(user.id, tenantId);
            res.status(200).json({
                success: true,
                data: { ...user, assignedRoles: roles },
            });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * POST /users
     * Crear usuario
     */
    router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), 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,
                tenantId,
            };
            if (!dto.email || !dto.password || !dto.firstName || !dto.lastName) {
                res.status(400).json({
                    error: 'Bad Request',
                    message: 'Email, password, firstName and lastName are required',
                });
                return;
            }
            const user = await usersService.create(dto, req.user?.sub);
            res.status(201).json({ success: true, data: user });
        }
        catch (error) {
            if (error instanceof Error && error.message === 'Email already exists in this tenant') {
                res.status(409).json({ error: 'Conflict', message: error.message });
                return;
            }
            next(error);
        }
    });
    /**
     * PATCH /users/:id
     * Actualizar usuario
     */
    router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), 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 user = await usersService.update(req.params.id, tenantId, dto);
            res.status(200).json({ success: true, data: user });
        }
        catch (error) {
            if (error instanceof Error && error.message === 'User not found') {
                res.status(404).json({ error: 'Not Found', message: error.message });
                return;
            }
            next(error);
        }
    });
    /**
     * DELETE /users/:id
     * Eliminar usuario (soft delete)
     */
    router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            await usersService.delete(req.params.id, tenantId, req.user?.sub);
            res.status(200).json({ success: true, message: 'User deleted' });
        }
        catch (error) {
            if (error instanceof Error && error.message === 'User not found') {
                res.status(404).json({ error: 'Not Found', message: error.message });
                return;
            }
            next(error);
        }
    });
    /**
     * POST /users/:id/roles
     * Asignar rol a usuario
     */
    router.post('/:id/roles', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const { roleCode } = req.body;
            if (!roleCode) {
                res.status(400).json({ error: 'Bad Request', message: 'roleCode is required' });
                return;
            }
            const userRole = await usersService.assignRole({ userId: req.params.id, roleCode, tenantId }, req.user?.sub);
            res.status(200).json({ success: true, data: userRole });
        }
        catch (error) {
            if (error instanceof Error && error.message === 'Role not found') {
                res.status(404).json({ error: 'Not Found', message: error.message });
                return;
            }
            next(error);
        }
    });
    /**
     * DELETE /users/:id/roles/:roleCode
     * Remover rol de usuario
     */
    router.delete('/:id/roles/:roleCode', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), async (req, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            await usersService.removeRole(req.params.id, req.params.roleCode, tenantId);
            res.status(200).json({ success: true, message: 'Role removed' });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /users/:id/roles
     * Obtener roles de usuario
     */
    router.get('/:id/roles', 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 roles = await usersService.getUserRoles(req.params.id, tenantId);
            res.status(200).json({ success: true, data: roles });
        }
        catch (error) {
            next(error);
        }
    });
    return router;
}
exports.default = createUsersController;
//# sourceMappingURL=users.controller.js.map