/**
 * FondoGarantiaController - Controller de fondos de garantía
 *
 * Endpoints REST para gestión de fondos de garantía de contratos.
 *
 * @module Estimates
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { FondoGarantiaService, CreateFondoGarantiaDto, ReleaseFondoDto } from '../services/fondo-garantia.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 createFondoGarantiaController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const fondoGarantiaService = new FondoGarantiaService(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 /fondos-garantia
   */
  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 result = await fondoGarantiaService.findAll(getContext(req), 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 /fondos-garantia/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 stats = await fondoGarantiaService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /fondos-garantia/contrato/:contratoId
   */
  router.get('/contrato/:contratoId', 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 fondo = await fondoGarantiaService.findByContrato(getContext(req), req.params.contratoId);
      if (!fondo) {
        res.status(404).json({ error: 'Not Found', message: 'Guarantee fund not found' });
        return;
      }

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

  /**
   * GET /fondos-garantia/: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 fondo = await fondoGarantiaService.findById(getContext(req), req.params.id);
      if (!fondo) {
        res.status(404).json({ error: 'Not Found', message: 'Guarantee fund not found' });
        return;
      }

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

  /**
   * POST /fondos-garantia
   */
  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: CreateFondoGarantiaDto = req.body;
      if (!dto.contratoId) {
        res.status(400).json({ error: 'Bad Request', message: 'contratoId is required' });
        return;
      }

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

  /**
   * POST /fondos-garantia/:contratoId/accumulate
   */
  router.post('/:contratoId/accumulate', 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 { amount } = req.body;
      if (amount === undefined || amount <= 0) {
        res.status(400).json({ error: 'Bad Request', message: 'Valid amount is required' });
        return;
      }

      const fondo = await fondoGarantiaService.addAccumulation(
        getContext(req),
        req.params.contratoId,
        amount
      );

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

  /**
   * POST /fondos-garantia/:contratoId/release
   */
  router.post('/:contratoId/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 releasedById = req.user?.sub;
      if (!releasedById) {
        res.status(400).json({ error: 'Bad Request', message: 'User ID required' });
        return;
      }

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

      const dto: ReleaseFondoDto = {
        amount,
        releasedById,
        releaseDate: releaseDate ? new Date(releaseDate) : undefined,
        notes,
      };

      const fondo = await fondoGarantiaService.releasePartial(
        getContext(req),
        req.params.contratoId,
        dto
      );

      res.status(200).json({ success: true, data: fondo });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('no encontrado')) {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('excede')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * POST /fondos-garantia/:contratoId/release-full
   */
  router.post('/:contratoId/release-full', 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 releasedById = req.user?.sub;
      if (!releasedById) {
        res.status(400).json({ error: 'Bad Request', message: 'User ID required' });
        return;
      }

      const { releaseDate } = req.body;

      const fondo = await fondoGarantiaService.releaseFull(
        getContext(req),
        req.params.contratoId,
        releasedById,
        releaseDate ? new Date(releaseDate) : undefined
      );

      res.status(200).json({ success: true, data: fondo });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('no encontrado')) {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('pendiente')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * DELETE /fondos-garantia/: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 fondoGarantiaService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Guarantee fund not found' });
        return;
      }

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

  return router;
}

export default createFondoGarantiaController;
