/**
 * EmployeeController - Controller de empleados
 *
 * Endpoints REST para gestión de empleados y asignaciones a obras.
 *
 * @module HR
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  EmployeeService,
  CreateEmployeeDto,
  UpdateEmployeeDto,
  AssignFraccionamientoDto,
  EmployeeFilters,
} from '../services/employee.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

/**
 * Local service context interface
 */
interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

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

  // Servicios
  const employeeService = new EmployeeService(dataSource);
  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 /empleados
   * Listar empleados 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: EmployeeFilters = {
        estado: req.query.estado as any,
        puestoId: req.query.puestoId as string,
        departamento: req.query.departamento as string,
        fraccionamientoId: req.query.fraccionamientoId as string,
        search: req.query.search as string,
      };

      const result = await employeeService.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 /empleados/stats
   * Obtener estadísticas de empleados
   */
  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 stats = await employeeService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /empleados/by-fraccionamiento/:fraccionamientoId
   * Obtener empleados asignados a un fraccionamiento
   */
  router.get('/by-fraccionamiento/:fraccionamientoId', 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 employees = await employeeService.getEmployeesByFraccionamiento(
        getContext(req),
        req.params.fraccionamientoId
      );
      res.status(200).json({ success: true, data: employees });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /empleados/:id
   * Obtener empleado por ID 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 employee = await employeeService.findById(getContext(req), req.params.id);
      if (!employee) {
        res.status(404).json({ error: 'Not Found', message: 'Employee not found' });
        return;
      }

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

  /**
   * POST /empleados
   * Crear empleado
   */
  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: CreateEmployeeDto = req.body;

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

      const employee = await employeeService.create(getContext(req), dto);
      res.status(201).json({ success: true, data: employee });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PATCH /empleados/:id
   * Actualizar empleado
   */
  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: UpdateEmployeeDto = req.body;
      const employee = await employeeService.update(getContext(req), req.params.id, dto);

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

      res.status(200).json({ success: true, data: employee });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /empleados/:id/status
   * Cambiar estado del empleado
   */
  router.post('/:id/status', 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 { estado, fechaBaja } = req.body;

      if (!estado || !['activo', 'inactivo', 'baja'].includes(estado)) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'estado must be one of: activo, inactivo, baja',
        });
        return;
      }

      const employee = await employeeService.changeStatus(
        getContext(req),
        req.params.id,
        estado,
        fechaBaja ? new Date(fechaBaja) : undefined
      );

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

      res.status(200).json({
        success: true,
        data: employee,
        message: `Employee status changed to ${estado}`,
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /empleados/:id/assign
   * Asignar empleado a fraccionamiento
   */
  router.post('/:id/assign', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', '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: AssignFraccionamientoDto = req.body;

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

      dto.fechaInicio = new Date(dto.fechaInicio);
      if (dto.fechaFin) {
        dto.fechaFin = new Date(dto.fechaFin);
      }

      const asignacion = await employeeService.assignToFraccionamiento(
        getContext(req),
        req.params.id,
        dto
      );

      res.status(201).json({
        success: true,
        data: asignacion,
        message: 'Employee assigned to project',
      });
    } catch (error) {
      if (error instanceof Error && error.message === 'Employee not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /empleados/:id/assign/:fraccionamientoId
   * Remover empleado de fraccionamiento
   */
  router.delete('/:id/assign/:fraccionamientoId', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', '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 employeeService.removeFromFraccionamiento(
        getContext(req),
        req.params.id,
        req.params.fraccionamientoId
      );

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

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

  return router;
}

export default createEmployeeController;
