/**
 * UsersController - Controlador de usuarios
 *
 * Endpoints REST para CRUD de usuarios y asignación de roles.
 *
 * @module Users
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { UsersService, CreateUserDto, UpdateUserDto } from '../services/users.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { Role } from '../../auth/entities/role.entity';
import { UserRole } from '../../auth/entities/user-role.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

/**
 * Crear router de usuarios
 */
export function createUsersController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const roleRepository = dataSource.getRepository(Role);
  const userRoleRepository = dataSource.getRepository(UserRole);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const usersService = new UsersService(userRepository, roleRepository, userRoleRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  /**
   * GET /users
   * Listar usuarios del tenant
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    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 as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);
      const search = req.query.search as string;
      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: Request, res: Response, next: NextFunction): Promise<void> => {
    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: Request, res: Response, next: NextFunction): Promise<void> => {
    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: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: CreateUserDto = {
        ...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: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: UpdateUserDto = 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: Request, res: Response, next: NextFunction): Promise<void> => {
    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: Request, res: Response, next: NextFunction): Promise<void> => {
    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: Request, res: Response, next: NextFunction): Promise<void> => {
    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: Request, res: Response, next: NextFunction): Promise<void> => {
    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;
}

export default createUsersController;
