/**
 * AnticipoController - Controller de anticipos de obra
 *
 * Endpoints REST para gestión de anticipos de contratos de construcción.
 *
 * @module Estimates
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { AnticipoService, CreateAnticipoDto, AnticipoFilters } from '../services/anticipo.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';

interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

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

  // Servicios
  const anticipoService = new AnticipoService(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 /anticipos
   */
  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: AnticipoFilters = {};
      if (req.query.contratoId) filters.contratoId = req.query.contratoId as string;
      if (req.query.advanceType) filters.advanceType = req.query.advanceType as any;
      if (req.query.isFullyAmortized !== undefined) {
        filters.isFullyAmortized = req.query.isFullyAmortized === 'true';
      }
      if (req.query.startDate) filters.startDate = new Date(req.query.startDate as string);
      if (req.query.endDate) filters.endDate = new Date(req.query.endDate as string);

      const result = await anticipoService.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 /anticipos/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: AnticipoFilters = {};
      if (req.query.contratoId) filters.contratoId = req.query.contratoId as string;
      if (req.query.advanceType) filters.advanceType = req.query.advanceType as any;

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

  /**
   * GET /anticipos/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 page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const result = await anticipoService.findByContrato(
        getContext(req),
        req.params.contratoId,
        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 /anticipos/: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 anticipo = await anticipoService.findById(getContext(req), req.params.id);
      if (!anticipo) {
        res.status(404).json({ error: 'Not Found', message: 'Anticipo not found' });
        return;
      }

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

  /**
   * POST /anticipos
   */
  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: CreateAnticipoDto = req.body;

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

      const anticipo = await anticipoService.createAnticipo(getContext(req), dto);
      res.status(201).json({ success: true, data: anticipo });
    } catch (error) {
      if (error instanceof Error && error.message.includes('no coincide')) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

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

      const anticipo = await anticipoService.approveAnticipo(
        getContext(req),
        req.params.id,
        approvedById,
        req.body.notes
      );

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

  /**
   * POST /anticipos/:id/pay
   */
  router.post('/:id/pay', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'accountant'), 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 { paymentReference, paidAt } = req.body;
      if (!paymentReference) {
        res.status(400).json({ error: 'Bad Request', message: 'paymentReference is required' });
        return;
      }

      const anticipo = await anticipoService.markPaid(
        getContext(req),
        req.params.id,
        paymentReference,
        paidAt ? new Date(paidAt) : undefined
      );

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

  /**
   * POST /anticipos/:id/amortize
   */
  router.post('/:id/amortize', 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 anticipo = await anticipoService.updateAmortization(
        getContext(req),
        req.params.id,
        amount
      );

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

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

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

  return router;
}

export default createAnticipoController;
