/**
 * IncidenteController - Controller de incidentes HSE
 *
 * Endpoints REST para gestión de incidentes de seguridad.
 * Workflow: abierto -> en_investigacion -> cerrado
 *
 * @module HSE
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  IncidenteService,
  CreateIncidenteDto,
  UpdateIncidenteDto,
  AddInvolucradoDto,
  AddAccionDto,
  UpdateAccionDto,
  IncidenteFilters,
} from '../services/incidente.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Incidente } from '../entities/incidente.entity';
import { IncidenteInvolucrado } from '../entities/incidente-involucrado.entity';
import { IncidenteAccion } from '../entities/incidente-accion.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

/**
 * Service context for multi-tenant operations
 */
interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

  // Repositorios
  const incidenteRepository = dataSource.getRepository(Incidente);
  const involucradoRepository = dataSource.getRepository(IncidenteInvolucrado);
  const accionRepository = dataSource.getRepository(IncidenteAccion);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const incidenteService = new IncidenteService(
    incidenteRepository,
    involucradoRepository,
    accionRepository
  );
  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 /incidentes
   * Listar incidentes 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: IncidenteFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        tipo: req.query.tipo as any,
        gravedad: req.query.gravedad as any,
        estado: req.query.estado as any,
        dateFrom: req.query.dateFrom ? new Date(req.query.dateFrom as string) : undefined,
        dateTo: req.query.dateTo ? new Date(req.query.dateTo as string) : undefined,
      };

      const result = await incidenteService.findWithFilters(getContext(req), filters, page, limit);

      res.status(200).json({
        success: true,
        data: result.data,
        pagination: {
          total: result.total,
          page: result.page,
          limit: result.limit,
          totalPages: result.totalPages,
        },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /incidentes/stats
   * Obtener estadísticas de incidentes
   */
  router.get('/stats', 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 fraccionamientoId = req.query.fraccionamientoId as string;
      const stats = await incidenteService.getStats(getContext(req), fraccionamientoId);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /incidentes/:id
   * Obtener incidente con detalles completos
   */
  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 incidente = await incidenteService.findWithDetails(getContext(req), req.params.id);
      if (!incidente) {
        res.status(404).json({ error: 'Not Found', message: 'Incident not found' });
        return;
      }

      res.status(200).json({ success: true, data: incidente });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /incidentes
   * Crear incidente
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'resident'), 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: CreateIncidenteDto = req.body;

      if (!dto.fechaHora || !dto.fraccionamientoId || !dto.tipo || !dto.gravedad || !dto.descripcion) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'fechaHora, fraccionamientoId, tipo, gravedad and descripcion are required',
        });
        return;
      }

      dto.fechaHora = new Date(dto.fechaHora);
      const incidente = await incidenteService.create(getContext(req), dto);
      res.status(201).json({ success: true, data: incidente });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /incidentes/:id
   * Actualizar incidente
   */
  router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'resident'), 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: UpdateIncidenteDto = req.body;
      const incidente = await incidenteService.update(getContext(req), req.params.id, dto);

      if (!incidente) {
        res.status(404).json({ error: 'Not Found', message: 'Incident not found' });
        return;
      }

      res.status(200).json({ success: true, data: incidente });
    } catch (error) {
      if (error instanceof Error && error.message.includes('closed')) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /incidentes/:id/investigate
   * Iniciar investigación del incidente
   */
  router.post('/:id/investigate', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', '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 incidente = await incidenteService.startInvestigation(getContext(req), req.params.id);
      if (!incidente) {
        res.status(404).json({ error: 'Not Found', message: 'Incident not found' });
        return;
      }

      res.status(200).json({ success: true, data: incidente, message: 'Investigation started' });
    } catch (error) {
      if (error instanceof Error && error.message.includes('only start')) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /incidentes/:id/close
   * Cerrar incidente
   */
  router.post('/:id/close', 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 incidente = await incidenteService.closeIncident(getContext(req), req.params.id);
      if (!incidente) {
        res.status(404).json({ error: 'Not Found', message: 'Incident not found' });
        return;
      }

      res.status(200).json({ success: true, data: incidente, message: 'Incident closed' });
    } catch (error) {
      if (error instanceof Error && (error.message.includes('already closed') || error.message.includes('pending actions'))) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /incidentes/:id/involucrados
   * Agregar involucrado al incidente
   */
  router.post('/:id/involucrados', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'resident'), 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: AddInvolucradoDto = req.body;

      if (!dto.employeeId || !dto.rol) {
        res.status(400).json({ error: 'Bad Request', message: 'employeeId and rol are required' });
        return;
      }

      const involucrado = await incidenteService.addInvolucrado(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: involucrado });
    } catch (error) {
      if (error instanceof Error && error.message === 'Incidente not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /incidentes/:id/involucrados/:involucradoId
   * Remover involucrado del incidente
   */
  router.delete('/:id/involucrados/:involucradoId', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), 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 removed = await incidenteService.removeInvolucrado(
        getContext(req),
        req.params.id,
        req.params.involucradoId
      );

      if (!removed) {
        res.status(404).json({ error: 'Not Found', message: 'Involved person not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Involved person removed' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /incidentes/:id/acciones
   * Agregar acción correctiva al incidente
   */
  router.post('/:id/acciones', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', '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: AddAccionDto = req.body;

      if (!dto.descripcion || !dto.tipo || !dto.fechaCompromiso) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'descripcion, tipo and fechaCompromiso are required',
        });
        return;
      }

      dto.fechaCompromiso = new Date(dto.fechaCompromiso);
      const accion = await incidenteService.addAccion(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: accion });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Incidente not found') {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('closed')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * PATCH /incidentes/:id/acciones/:accionId
   * Actualizar acción correctiva
   */
  router.patch('/:id/acciones/:accionId', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', '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: UpdateAccionDto = req.body;
      if (dto.fechaCompromiso) {
        dto.fechaCompromiso = new Date(dto.fechaCompromiso);
      }

      const accion = await incidenteService.updateAccion(
        getContext(req),
        req.params.id,
        req.params.accionId,
        dto
      );

      if (!accion) {
        res.status(404).json({ error: 'Not Found', message: 'Action not found' });
        return;
      }

      res.status(200).json({ success: true, data: accion });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createIncidenteController;
