/**
 * StpsController - Controller de cumplimiento STPS
 *
 * Endpoints REST para gestión de normas, comisiones y auditorías STPS.
 *
 * @module HSE
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  StpsService,
  CreateCumplimientoDto,
  CreateComisionDto,
  AddIntegranteDto,
  CreateRecorridoDto,
  CreateProgramaDto,
  CreateActividadDto,
  CreateAuditoriaDto,
  CreateDocumentoDto,
  CumplimientoFilters,
  ComisionFilters,
  AuditoriaFilters,
} from '../services/stps.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { NormaStps } from '../entities/norma-stps.entity';
import { NormaRequisito } from '../entities/norma-requisito.entity';
import { CumplimientoObra, EstadoCumplimiento } from '../entities/cumplimiento-obra.entity';
import { ComisionSeguridad, EstadoComision } from '../entities/comision-seguridad.entity';
import { ComisionIntegrante } from '../entities/comision-integrante.entity';
import { ComisionRecorrido } from '../entities/comision-recorrido.entity';
import { ProgramaSeguridad } from '../entities/programa-seguridad.entity';
import { ProgramaActividad, EstadoActividad } from '../entities/programa-actividad.entity';
import { DocumentoStps } from '../entities/documento-stps.entity';
import { Auditoria, ResultadoAuditoria } from '../entities/auditoria.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 STPS
 */
export function createStpsController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const normaRepository = dataSource.getRepository(NormaStps);
  const requisitoRepository = dataSource.getRepository(NormaRequisito);
  const cumplimientoRepository = dataSource.getRepository(CumplimientoObra);
  const comisionRepository = dataSource.getRepository(ComisionSeguridad);
  const integranteRepository = dataSource.getRepository(ComisionIntegrante);
  const recorridoRepository = dataSource.getRepository(ComisionRecorrido);
  const programaRepository = dataSource.getRepository(ProgramaSeguridad);
  const actividadRepository = dataSource.getRepository(ProgramaActividad);
  const documentoRepository = dataSource.getRepository(DocumentoStps);
  const auditoriaRepository = dataSource.getRepository(Auditoria);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const stpsService = new StpsService(
    normaRepository,
    requisitoRepository,
    cumplimientoRepository,
    comisionRepository,
    integranteRepository,
    recorridoRepository,
    programaRepository,
    actividadRepository,
    documentoRepository,
    auditoriaRepository
  );
  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,
    };
  };

  // ========== Normas y Requisitos ==========

  /**
   * GET /stps/normas
   * Listar normas STPS
   */
  router.get('/normas', authMiddleware.authenticate, async (_req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const normas = await stpsService.findNormas();
      res.status(200).json({ success: true, data: normas });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /stps/normas/:id
   * Obtener norma con requisitos
   */
  router.get('/normas/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const norma = await stpsService.findNormaById(req.params.id);
      if (!norma) {
        res.status(404).json({ error: 'Not Found', message: 'Norm not found' });
        return;
      }
      res.status(200).json({ success: true, data: norma });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /stps/normas/:id/requisitos
   * Listar requisitos de una norma
   */
  router.get('/normas/:id/requisitos', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const requisitos = await stpsService.findRequisitosByNorma(req.params.id);
      res.status(200).json({ success: true, data: requisitos });
    } catch (error) {
      next(error);
    }
  });

  // ========== Cumplimiento por Obra ==========

  /**
   * GET /stps/cumplimiento
   * Listar estado de cumplimiento
   */
  router.get('/cumplimiento', 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: CumplimientoFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        normaId: req.query.normaId as string,
        estado: req.query.estado as EstadoCumplimiento,
      };

      const result = await stpsService.findCumplimientos(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);
    }
  });

  /**
   * POST /stps/cumplimiento
   * Registrar evaluación de cumplimiento
   */
  router.post('/cumplimiento', 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 dto: CreateCumplimientoDto = req.body;

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

      dto.fechaEvaluacion = new Date(dto.fechaEvaluacion);
      if (dto.fechaCompromiso) dto.fechaCompromiso = new Date(dto.fechaCompromiso);
      const cumplimiento = await stpsService.createCumplimiento(getContext(req), dto);
      res.status(201).json({ success: true, data: cumplimiento });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /stps/cumplimiento/:id
   * Actualizar estado de cumplimiento
   */
  router.patch('/cumplimiento/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { estado, evidenciaUrl, observaciones } = req.body;
      if (!estado) {
        res.status(400).json({ error: 'Bad Request', message: 'estado is required' });
        return;
      }

      const cumplimiento = await stpsService.updateCumplimientoEstado(
        getContext(req),
        req.params.id,
        estado,
        evidenciaUrl,
        observaciones
      );
      if (!cumplimiento) {
        res.status(404).json({ error: 'Not Found', message: 'Compliance record not found' });
        return;
      }
      res.status(200).json({ success: true, data: cumplimiento });
    } catch (error) {
      next(error);
    }
  });

  // ========== Comisiones de Seguridad ==========

  /**
   * GET /stps/comisiones
   * Listar comisiones de seguridad
   */
  router.get('/comisiones', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const filters: ComisionFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        estado: req.query.estado as EstadoComision,
      };

      const comisiones = await stpsService.findComisiones(getContext(req), filters);
      res.status(200).json({ success: true, data: comisiones });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /stps/comisiones/:id
   * Obtener comisión con integrantes
   */
  router.get('/comisiones/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const comision = await stpsService.findComisionById(getContext(req), req.params.id);
      if (!comision) {
        res.status(404).json({ error: 'Not Found', message: 'Commission not found' });
        return;
      }
      res.status(200).json({ success: true, data: comision });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/comisiones
   * Crear comisión de seguridad
   */
  router.post('/comisiones', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateComisionDto = req.body;

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

      dto.fechaConstitucion = new Date(dto.fechaConstitucion);
      dto.vigenciaInicio = new Date(dto.vigenciaInicio);
      dto.vigenciaFin = new Date(dto.vigenciaFin);
      const comision = await stpsService.createComision(getContext(req), dto);
      res.status(201).json({ success: true, data: comision });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /stps/comisiones/:id/estado
   * Actualizar estado de comisión
   */
  router.patch('/comisiones/:id/estado', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { estado } = req.body;
      if (!estado) {
        res.status(400).json({ error: 'Bad Request', message: 'estado is required' });
        return;
      }

      const comision = await stpsService.updateComisionEstado(getContext(req), req.params.id, estado);
      if (!comision) {
        res.status(404).json({ error: 'Not Found', message: 'Commission not found' });
        return;
      }
      res.status(200).json({ success: true, data: comision });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/comisiones/:id/integrantes
   * Agregar integrante a comisión
   */
  router.post('/comisiones/:id/integrantes', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: AddIntegranteDto = req.body;

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

      dto.fechaNombramiento = new Date(dto.fechaNombramiento);
      const integrante = await stpsService.addIntegrante(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: integrante });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /stps/comisiones/integrantes/:integranteId
   * Desactivar integrante de comisión
   */
  router.delete('/comisiones/integrantes/:integranteId', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const removed = await stpsService.removeIntegrante(getContext(req), req.params.integranteId);
      if (!removed) {
        res.status(404).json({ error: 'Not Found', message: 'Member not found' });
        return;
      }
      res.status(200).json({ success: true, message: 'Member deactivated' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/comisiones/:id/recorridos
   * Programar recorrido de verificación
   */
  router.post('/comisiones/:id/recorridos', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateRecorridoDto = {
        ...req.body,
        comisionId: req.params.id,
      };

      if (!dto.fechaProgramada) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'fechaProgramada is required',
        });
        return;
      }

      dto.fechaProgramada = new Date(dto.fechaProgramada);
      const recorrido = await stpsService.createRecorrido(getContext(req), dto);
      res.status(201).json({ success: true, data: recorrido });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/recorridos/:id/completar
   * Completar recorrido de verificación
   */
  router.post('/recorridos/:id/completar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { hallazgos, recomendaciones, numeroActa, documentoActaUrl } = req.body;

      const recorrido = await stpsService.completarRecorrido(
        getContext(req),
        req.params.id,
        hallazgos,
        recomendaciones,
        numeroActa,
        documentoActaUrl
      );
      if (!recorrido) {
        res.status(404).json({ error: 'Not Found', message: 'Tour not found' });
        return;
      }
      res.status(200).json({ success: true, data: recorrido, message: 'Tour completed' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/recorridos/:id/cancelar
   * Cancelar recorrido
   */
  router.post('/recorridos/:id/cancelar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const recorrido = await stpsService.cancelarRecorrido(getContext(req), req.params.id);
      if (!recorrido) {
        res.status(404).json({ error: 'Not Found', message: 'Tour not found' });
        return;
      }
      res.status(200).json({ success: true, data: recorrido, message: 'Tour cancelled' });
    } catch (error) {
      next(error);
    }
  });

  // ========== Programas de Seguridad ==========

  /**
   * GET /stps/programas
   * Listar programas de seguridad
   */
  router.get('/programas', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const fraccionamientoId = req.query.fraccionamientoId as string;
      const anio = req.query.anio ? parseInt(req.query.anio as string) : undefined;
      const programas = await stpsService.findProgramas(getContext(req), fraccionamientoId, anio);
      res.status(200).json({ success: true, data: programas });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /stps/programas/:id
   * Obtener programa con actividades
   */
  router.get('/programas/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const programa = await stpsService.findProgramaById(getContext(req), req.params.id);
      if (!programa) {
        res.status(404).json({ error: 'Not Found', message: 'Program not found' });
        return;
      }
      res.status(200).json({ success: true, data: programa });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/programas
   * Crear programa de seguridad
   */
  router.post('/programas', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateProgramaDto = req.body;

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

      const programa = await stpsService.createPrograma(getContext(req), dto);
      res.status(201).json({ success: true, data: programa });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/programas/:id/aprobar
   * Aprobar programa de seguridad
   */
  router.post('/programas/:id/aprobar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const programa = await stpsService.aprobarPrograma(getContext(req), req.params.id);
      if (!programa) {
        res.status(404).json({ error: 'Not Found', message: 'Program not found' });
        return;
      }
      res.status(200).json({ success: true, data: programa, message: 'Program approved' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/programas/:id/finalizar
   * Finalizar programa de seguridad
   */
  router.post('/programas/:id/finalizar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const programa = await stpsService.finalizarPrograma(getContext(req), req.params.id);
      if (!programa) {
        res.status(404).json({ error: 'Not Found', message: 'Program not found' });
        return;
      }
      res.status(200).json({ success: true, data: programa, message: 'Program finalized' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/programas/:id/actividades
   * Agregar actividad al programa
   */
  router.post('/programas/:id/actividades', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateActividadDto = {
        ...req.body,
        programaId: req.params.id,
      };

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

      dto.fechaProgramada = new Date(dto.fechaProgramada);
      const actividad = await stpsService.createActividad(getContext(req), dto);
      res.status(201).json({ success: true, data: actividad });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /stps/actividades/:id/estado
   * Actualizar estado de actividad
   */
  router.patch('/actividades/:id/estado', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { estado } = req.body;
      if (!estado) {
        res.status(400).json({ error: 'Bad Request', message: 'estado is required' });
        return;
      }

      const actividad = await stpsService.updateActividadEstado(getContext(req), req.params.id, estado as EstadoActividad);
      if (!actividad) {
        res.status(404).json({ error: 'Not Found', message: 'Activity not found' });
        return;
      }
      res.status(200).json({ success: true, data: actividad });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/actividades/:id/completar
   * Completar actividad
   */
  router.post('/actividades/:id/completar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { evidenciaUrl } = req.body;

      const actividad = await stpsService.completarActividad(getContext(req), req.params.id, evidenciaUrl);
      if (!actividad) {
        res.status(404).json({ error: 'Not Found', message: 'Activity not found' });
        return;
      }
      res.status(200).json({ success: true, data: actividad, message: 'Activity completed' });
    } catch (error) {
      next(error);
    }
  });

  // ========== Documentos STPS ==========

  /**
   * GET /stps/documentos
   * Listar documentos STPS
   */
  router.get('/documentos', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const fraccionamientoId = req.query.fraccionamientoId as string;
      const tipo = req.query.tipo as any;
      const documentos = await stpsService.findDocumentos(getContext(req), fraccionamientoId, tipo);
      res.status(200).json({ success: true, data: documentos });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /stps/documentos/:id
   * Obtener documento por ID
   */
  router.get('/documentos/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const documento = await stpsService.findDocumentoById(getContext(req), req.params.id);
      if (!documento) {
        res.status(404).json({ error: 'Not Found', message: 'Document not found' });
        return;
      }
      res.status(200).json({ success: true, data: documento });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/documentos
   * Crear documento STPS
   */
  router.post('/documentos', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateDocumentoDto = req.body;

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

      dto.fechaEmision = new Date(dto.fechaEmision);
      if (dto.fechaVencimiento) dto.fechaVencimiento = new Date(dto.fechaVencimiento);
      const documento = await stpsService.createDocumento(getContext(req), dto);
      res.status(201).json({ success: true, data: documento });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/documentos/:id/firmar
   * Marcar documento como firmado
   */
  router.post('/documentos/:id/firmar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const documento = await stpsService.marcarDocumentoFirmado(getContext(req), req.params.id);
      if (!documento) {
        res.status(404).json({ error: 'Not Found', message: 'Document not found' });
        return;
      }
      res.status(200).json({ success: true, data: documento, message: 'Document signed' });
    } catch (error) {
      next(error);
    }
  });

  // ========== Auditorías ==========

  /**
   * GET /stps/auditorias
   * Listar auditorías
   */
  router.get('/auditorias', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const filters: AuditoriaFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        tipo: req.query.tipo as any,
        resultado: req.query.resultado as ResultadoAuditoria,
        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 stpsService.findAuditorias(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 /stps/auditorias/:id
   * Obtener auditoría por ID
   */
  router.get('/auditorias/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const auditoria = await stpsService.findAuditoriaById(getContext(req), req.params.id);
      if (!auditoria) {
        res.status(404).json({ error: 'Not Found', message: 'Audit not found' });
        return;
      }
      res.status(200).json({ success: true, data: auditoria });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/auditorias
   * Programar auditoría
   */
  router.post('/auditorias', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateAuditoriaDto = req.body;

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

      dto.fechaProgramada = new Date(dto.fechaProgramada);
      const auditoria = await stpsService.createAuditoria(getContext(req), dto);
      res.status(201).json({ success: true, data: auditoria });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /stps/auditorias/:id/completar
   * Completar auditoría
   */
  router.post('/auditorias/:id/completar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { resultado, noConformidades, observaciones, informeUrl } = req.body;

      if (!resultado || noConformidades === undefined) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'resultado and noConformidades are required',
        });
        return;
      }

      const auditoria = await stpsService.completarAuditoria(
        getContext(req),
        req.params.id,
        resultado,
        noConformidades,
        observaciones,
        informeUrl
      );
      if (!auditoria) {
        res.status(404).json({ error: 'Not Found', message: 'Audit not found' });
        return;
      }
      res.status(200).json({ success: true, data: auditoria, message: 'Audit completed' });
    } catch (error) {
      next(error);
    }
  });

  // ========== Estadísticas ==========

  /**
   * GET /stps/stats
   * Obtener estadísticas STPS
   */
  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 stpsService.getStats(getContext(req), fraccionamientoId);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createStpsController;
