/**
 * AmbientalController - Controller de gestión ambiental HSE
 *
 * Endpoints REST para gestión de residuos y manifiestos.
 *
 * @module HSE
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  AmbientalService,
  CreateResiduoCatalogoDto,
  CreateGeneracionDto,
  CreateManifiestoDto,
  AddDetalleManifiestoDto,
  CreateImpactoDto,
  CreateQuejaDto,
  ResiduoFilters,
  GeneracionFilters,
  ManifiestoFilters,
  ImpactoFilters,
  QuejaFilters,
} from '../services/ambiental.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { ResiduoCatalogo } from '../entities/residuo-catalogo.entity';
import { ResiduoGeneracion, EstadoResiduo } from '../entities/residuo-generacion.entity';
import { AlmacenTemporal } from '../entities/almacen-temporal.entity';
import { ProveedorAmbiental } from '../entities/proveedor-ambiental.entity';
import { ManifiestoResiduos, EstadoManifiesto } from '../entities/manifiesto-residuos.entity';
import { ManifiestoDetalle } from '../entities/manifiesto-detalle.entity';
import { ImpactoAmbiental, EstadoImpacto } from '../entities/impacto-ambiental.entity';
import { QuejaAmbiental } from '../entities/queja-ambiental.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 gestión ambiental
 */
export function createAmbientalController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const residuoCatalogoRepository = dataSource.getRepository(ResiduoCatalogo);
  const generacionRepository = dataSource.getRepository(ResiduoGeneracion);
  const almacenRepository = dataSource.getRepository(AlmacenTemporal);
  const proveedorRepository = dataSource.getRepository(ProveedorAmbiental);
  const manifiestoRepository = dataSource.getRepository(ManifiestoResiduos);
  const detalleRepository = dataSource.getRepository(ManifiestoDetalle);
  const impactoRepository = dataSource.getRepository(ImpactoAmbiental);
  const quejaRepository = dataSource.getRepository(QuejaAmbiental);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const ambientalService = new AmbientalService(
    residuoCatalogoRepository,
    generacionRepository,
    almacenRepository,
    proveedorRepository,
    manifiestoRepository,
    detalleRepository,
    impactoRepository,
    quejaRepository
  );
  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,
    };
  };

  // ========== Catálogo de Residuos ==========

  /**
   * GET /ambiental/residuos/catalogo
   * Listar catálogo de residuos
   */
  router.get('/residuos/catalogo', 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: ResiduoFilters = {
        categoria: req.query.categoria as any,
        activo: req.query.activo === 'true' ? true : req.query.activo === 'false' ? false : undefined,
        search: req.query.search as string,
      };

      const result = await ambientalService.findResiduos(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 /ambiental/residuos/catalogo
   * Crear tipo de residuo en catálogo
   */
  router.post('/residuos/catalogo', authMiddleware.authenticate, authMiddleware.authorize('admin'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateResiduoCatalogoDto = req.body;

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

      const residuo = await ambientalService.createResiduo(dto);
      res.status(201).json({ success: true, data: residuo });
    } catch (error) {
      next(error);
    }
  });

  // ========== Generación de Residuos ==========

  /**
   * GET /ambiental/generaciones
   * Listar generaciones de residuos
   */
  router.get('/generaciones', 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: GeneracionFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        residuoId: req.query.residuoId as string,
        estado: req.query.estado as EstadoResiduo,
        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 ambientalService.findGeneraciones(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 /ambiental/generaciones
   * Registrar generación de residuo
   */
  router.post('/generaciones', 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: CreateGeneracionDto = req.body;

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

      dto.fechaGeneracion = new Date(dto.fechaGeneracion);
      const generacion = await ambientalService.createGeneracion(getContext(req), dto);
      res.status(201).json({ success: true, data: generacion });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /ambiental/generaciones/:id/estado
   * Actualizar estado de generación
   */
  router.patch('/generaciones/: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 generacion = await ambientalService.updateGeneracionEstado(getContext(req), req.params.id, estado);
      if (!generacion) {
        res.status(404).json({ error: 'Not Found', message: 'Waste generation not found' });
        return;
      }
      res.status(200).json({ success: true, data: generacion });
    } catch (error) {
      next(error);
    }
  });

  // ========== Almacenes Temporales ==========

  /**
   * GET /ambiental/almacenes
   * Listar almacenes temporales
   */
  router.get('/almacenes', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const fraccionamientoId = req.query.fraccionamientoId as string;
      const almacenes = await ambientalService.findAlmacenes(getContext(req), fraccionamientoId);
      res.status(200).json({ success: true, data: almacenes });
    } catch (error) {
      next(error);
    }
  });

  // ========== Proveedores Ambientales ==========

  /**
   * GET /ambiental/proveedores
   * Listar proveedores ambientales
   */
  router.get('/proveedores', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const proveedores = await ambientalService.findProveedores(getContext(req));
      res.status(200).json({ success: true, data: proveedores });
    } catch (error) {
      next(error);
    }
  });

  // ========== Manifiestos ==========

  /**
   * GET /ambiental/manifiestos
   * Listar manifiestos de residuos
   */
  router.get('/manifiestos', 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: ManifiestoFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        estado: req.query.estado as EstadoManifiesto,
        transportistaId: req.query.transportistaId 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 ambientalService.findManifiestos(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 /ambiental/manifiestos/:id
   * Obtener manifiesto con detalles
   */
  router.get('/manifiestos/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const manifiesto = await ambientalService.findManifiestoWithDetalles(getContext(req), req.params.id);
      if (!manifiesto) {
        res.status(404).json({ error: 'Not Found', message: 'Manifest not found' });
        return;
      }
      res.status(200).json({ success: true, data: manifiesto });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /ambiental/manifiestos
   * Crear manifiesto de residuos
   */
  router.post('/manifiestos', 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: CreateManifiestoDto = req.body;

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

      dto.fechaRecoleccion = new Date(dto.fechaRecoleccion);
      const manifiesto = await ambientalService.createManifiesto(getContext(req), dto);
      res.status(201).json({ success: true, data: manifiesto });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /ambiental/manifiestos/:id/detalles
   * Agregar detalle a manifiesto
   */
  router.post('/manifiestos/:id/detalles', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: AddDetalleManifiestoDto = req.body;

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

      const detalle = await ambientalService.addDetalleManifiesto(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: detalle });
    } catch (error) {
      if (error instanceof Error && error.message === 'Manifiesto no encontrado') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PATCH /ambiental/manifiestos/:id/estado
   * Actualizar estado de manifiesto
   */
  router.patch('/manifiestos/: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 manifiesto = await ambientalService.updateManifiestoEstado(getContext(req), req.params.id, estado);
      if (!manifiesto) {
        res.status(404).json({ error: 'Not Found', message: 'Manifest not found' });
        return;
      }
      res.status(200).json({ success: true, data: manifiesto });
    } catch (error) {
      next(error);
    }
  });

  // ========== Impactos Ambientales ==========

  /**
   * GET /ambiental/impactos
   * Listar impactos ambientales
   */
  router.get('/impactos', 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: ImpactoFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        tipoImpacto: req.query.tipoImpacto as any,
        nivelRiesgo: req.query.nivelRiesgo as any,
        estado: req.query.estado as any,
      };

      const result = await ambientalService.findImpactos(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 /ambiental/impactos
   * Crear impacto ambiental
   */
  router.post('/impactos', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateImpactoDto = req.body;

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

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

  /**
   * PATCH /ambiental/impactos/:id/estado
   * Actualizar estado de impacto
   */
  router.patch('/impactos/: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 impacto = await ambientalService.updateImpactoEstado(getContext(req), req.params.id, estado as EstadoImpacto);
      if (!impacto) {
        res.status(404).json({ error: 'Not Found', message: 'Impact not found' });
        return;
      }
      res.status(200).json({ success: true, data: impacto });
    } catch (error) {
      next(error);
    }
  });

  // ========== Quejas Ambientales ==========

  /**
   * GET /ambiental/quejas
   * Listar quejas ambientales
   */
  router.get('/quejas', 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: QuejaFilters = {
        fraccionamientoId: req.query.fraccionamientoId as string,
        tipo: req.query.tipo 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 ambientalService.findQuejas(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 /ambiental/quejas
   * Crear queja ambiental
   */
  router.post('/quejas', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const dto: CreateQuejaDto = req.body;

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

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

  /**
   * POST /ambiental/quejas/:id/atender
   * Atender queja ambiental
   */
  router.post('/quejas/:id/atender', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { accionesTomadas } = req.body;
      if (!accionesTomadas) {
        res.status(400).json({ error: 'Bad Request', message: 'accionesTomadas is required' });
        return;
      }

      const queja = await ambientalService.atenderQueja(getContext(req), req.params.id, accionesTomadas);
      if (!queja) {
        res.status(404).json({ error: 'Not Found', message: 'Complaint not found' });
        return;
      }
      res.status(200).json({ success: true, data: queja, message: 'Complaint being attended' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /ambiental/quejas/:id/cerrar
   * Cerrar queja ambiental
   */
  router.post('/quejas/:id/cerrar', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const queja = await ambientalService.cerrarQueja(getContext(req), req.params.id);
      if (!queja) {
        res.status(404).json({ error: 'Not Found', message: 'Complaint not found' });
        return;
      }
      res.status(200).json({ success: true, data: queja, message: 'Complaint closed' });
    } catch (error) {
      next(error);
    }
  });

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

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

  return router;
}

export default createAmbientalController;
