/**
 * RetencionController - Controller de retenciones
 *
 * Endpoints REST para gestión de retenciones de estimaciones.
 *
 * @module Estimates
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { RetencionService, CreateRetencionDto, ReleaseRetencionDto, RetencionFilters } from '../services/retencion.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 interface for service context
 */
interface ServiceContext {
  tenantId: string;
  userId?: string;
}

export function createRetencionController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const retencionService = new RetencionService(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 /retenciones
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.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: RetencionFilters = {};
      if (req.query.estimacionId) filters.estimacionId = req.query.estimacionId as string;
      if (req.query.contratoId) filters.contratoId = req.query.contratoId as string;
      if (req.query.retentionType) filters.retentionType = req.query.retentionType as any;
      if (req.query.isReleased !== undefined) {
        filters.isReleased = req.query.isReleased === 'true';
      }
      if (req.query.dateFrom) filters.dateFrom = new Date(req.query.dateFrom as string);
      if (req.query.dateTo) filters.dateTo = new Date(req.query.dateTo as string);

      const result = await retencionService.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 /retenciones/stats
   */
  router.get('/stats', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const filters: RetencionFilters = {};
      if (req.query.contratoId) filters.contratoId = req.query.contratoId as string;

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

  /**
   * GET /retenciones/contrato/:contratoId/totals
   */
  router.get('/contrato/:contratoId/totals', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const totals = await retencionService.getTotalByContrato(getContext(req), req.params.contratoId);
      res.status(200).json({ success: true, data: totals });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /retenciones/estimacion/:estimacionId
   */
  router.get('/estimacion/:estimacionId', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const retenciones = await retencionService.findByEstimacion(getContext(req), req.params.estimacionId);
      res.status(200).json({ success: true, data: retenciones });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /retenciones/:id
   */
  router.get('/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const retencion = await retencionService.findById(getContext(req), req.params.id);
      if (!retencion) {
        res.status(404).json({ error: 'Not Found', message: 'Retention not found' });
        return;
      }

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

  /**
   * POST /retenciones
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: CreateRetencionDto = req.body;
      if (!dto.estimacionId || !dto.retentionType || !dto.description || dto.amount === undefined) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'estimacionId, retentionType, description, and amount are required',
        });
        return;
      }

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

  /**
   * POST /retenciones/:id/release
   */
  router.post('/:id/release', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: ReleaseRetencionDto = req.body;
      if (dto.releasedAmount === undefined || dto.releasedAmount <= 0) {
        res.status(400).json({ error: 'Bad Request', message: 'Valid releasedAmount is required' });
        return;
      }

      const retencion = await retencionService.releaseRetencion(getContext(req), req.params.id, dto);
      if (!retencion) {
        res.status(404).json({ error: 'Not Found', message: 'Retention not found' });
        return;
      }

      res.status(200).json({ success: true, data: retencion });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('already released') || error.message.includes('exceed')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * DELETE /retenciones/:id
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const deleted = await retencionService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Retention not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Retention deleted' });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createRetencionController;
