/**
 * InspeccionController - Controller de inspecciones HSE
 *
 * Endpoints REST para gestión de inspecciones de seguridad y hallazgos.
 *
 * @module HSE
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  InspeccionService,
  CreateInspeccionDto,
  CreateHallazgoDto,
  InspeccionFilters,
  HallazgoFilters,
} from '../services/inspeccion.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Inspeccion } from '../entities/inspeccion.entity';
import { InspeccionEvaluacion } from '../entities/inspeccion-evaluacion.entity';
import { Hallazgo } from '../entities/hallazgo.entity';
import { HallazgoEvidencia } from '../entities/hallazgo-evidencia.entity';
import { TipoInspeccion } from '../entities/tipo-inspeccion.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 inspecciones
 */
export function createInspeccionController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const inspeccionRepository = dataSource.getRepository(Inspeccion);
  const evaluacionRepository = dataSource.getRepository(InspeccionEvaluacion);
  const hallazgoRepository = dataSource.getRepository(Hallazgo);
  const evidenciaRepository = dataSource.getRepository(HallazgoEvidencia);
  const tipoInspeccionRepository = dataSource.getRepository(TipoInspeccion);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const inspeccionService = new InspeccionService(
    inspeccionRepository,
    evaluacionRepository,
    hallazgoRepository,
    evidenciaRepository,
    tipoInspeccionRepository
  );
  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 /inspecciones/tipos
   * Listar tipos de inspección
   */
  router.get('/tipos', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tipos = await inspeccionService.findTiposInspeccion(getContext(req));
      res.status(200).json({ success: true, data: tipos });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /inspecciones
   * Listar inspecciones 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: InspeccionFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        tipoInspeccionId: req.query.tipoInspeccionId as string,
        estado: req.query.estado as string,
        inspectorId: req.query.inspectorId as string,
        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 inspeccionService.findInspecciones(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 /inspecciones/stats
   * Obtener estadísticas de inspecciones
   */
  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 inspeccionService.getStats(getContext(req), fraccionamientoId);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /inspecciones/:id
   * Obtener inspección con detalles
   */
  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 inspeccion = await inspeccionService.findInspeccionWithDetails(getContext(req), req.params.id);
      if (!inspeccion) {
        res.status(404).json({ error: 'Not Found', message: 'Inspection not found' });
        return;
      }

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

  /**
   * POST /inspecciones
   * Crear inspección
   */
  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: CreateInspeccionDto = req.body;

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

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

  /**
   * PATCH /inspecciones/:id/estado
   * Actualizar estado de inspección
   */
  router.patch('/:id/estado', 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 { estado } = req.body;
      if (!estado) {
        res.status(400).json({ error: 'Bad Request', message: 'estado is required' });
        return;
      }

      const inspeccion = await inspeccionService.updateInspeccionEstado(getContext(req), req.params.id, estado);
      if (!inspeccion) {
        res.status(404).json({ error: 'Not Found', message: 'Inspection not found' });
        return;
      }

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

  /**
   * PATCH /inspecciones/:id/observaciones
   * Actualizar observaciones de inspección
   */
  router.patch('/:id/observaciones', 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 { observaciones } = req.body;
      if (!observaciones) {
        res.status(400).json({ error: 'Bad Request', message: 'observaciones is required' });
        return;
      }

      const inspeccion = await inspeccionService.updateInspeccionObservaciones(getContext(req), req.params.id, observaciones);
      if (!inspeccion) {
        res.status(404).json({ error: 'Not Found', message: 'Inspection not found' });
        return;
      }

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

  // ========== Hallazgos ==========

  /**
   * GET /inspecciones/hallazgos
   * Listar hallazgos con filtros
   */
  router.get('/hallazgos/list', 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: HallazgoFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        gravedad: req.query.gravedad as any,
        estado: req.query.estado as any,
        responsableId: req.query.responsableId as string,
        vencidos: req.query.vencidos === 'true',
      };

      const result = await inspeccionService.findHallazgos(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 /inspecciones/:id/hallazgos
   * Agregar hallazgo a inspección
   */
  router.post('/:id/hallazgos', 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: CreateHallazgoDto = req.body;

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

      dto.fechaLimite = new Date(dto.fechaLimite);
      const hallazgo = await inspeccionService.createHallazgo(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: hallazgo });
    } catch (error) {
      if (error instanceof Error && error.message === 'Inspección no encontrada') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /inspecciones/hallazgos/:hallazgoId/correccion
   * Registrar corrección de hallazgo
   */
  router.post('/hallazgos/:hallazgoId/correccion', 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 { descripcionCorreccion } = req.body;
      if (!descripcionCorreccion) {
        res.status(400).json({ error: 'Bad Request', message: 'descripcionCorreccion is required' });
        return;
      }

      const hallazgo = await inspeccionService.registrarCorreccion(
        getContext(req),
        req.params.hallazgoId,
        descripcionCorreccion
      );

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

      res.status(200).json({ success: true, data: hallazgo, message: 'Correction registered' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /inspecciones/hallazgos/:hallazgoId/verificar
   * Verificar corrección de hallazgo
   */
  router.post('/hallazgos/:hallazgoId/verificar', 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 { aprobado } = req.body;
      if (aprobado === undefined) {
        res.status(400).json({ error: 'Bad Request', message: 'aprobado is required' });
        return;
      }

      const ctx = getContext(req);
      const hallazgo = await inspeccionService.verificarHallazgo(
        ctx,
        req.params.hallazgoId,
        ctx.userId || '',
        aprobado
      );

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

      res.status(200).json({
        success: true,
        data: hallazgo,
        message: aprobado ? 'Finding closed' : 'Finding reopened',
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createInspeccionController;
