/**
 * CapacitacionController - Controller de capacitaciones HSE
 *
 * Endpoints REST para gestión de catálogo de capacitaciones.
 *
 * @module HSE
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  CapacitacionService,
  CreateCapacitacionDto,
  UpdateCapacitacionDto,
  CapacitacionFilters,
} from '../services/capacitacion.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Capacitacion } from '../entities/capacitacion.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';
import { ServiceContext } from '../../../shared/services/base.service';

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

  // Repositorios
  const capacitacionRepository = dataSource.getRepository(Capacitacion);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const capacitacionService = new CapacitacionService(capacitacionRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper para crear contexto de servicio
  const getContext = (req: Request): ServiceContext => {
    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: 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 filters: CapacitacionFilters = {
        tipo: req.query.tipo as any,
        activo: req.query.activo === 'true' ? true : req.query.activo === 'false' ? false : undefined,
        search: req.query.search as string,
      };

      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: 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 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 as any);
      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: 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 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: 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: CreateCapacitacionDto = 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: 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: UpdateCapacitacionDto = 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: 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 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;
}

export default createCapacitacionController;
