/**
 * ReportController - Controller de Reportes
 *
 * Endpoints REST para gestión de reportes y ejecuciones.
 *
 * @module Reports
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { ReportService, CreateReportDto, UpdateReportDto, ReportFilters, ExecuteReportDto } from '../services/report.service';
import { EarnedValueService } from '../services/earned-value.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 createReportController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const reportService = new ReportService(dataSource);
  const evmService = new EarnedValueService(dataSource);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper para crear contexto
  const getContext = (req: Request): ServiceContext => {
    if (!req.tenantId) {
      throw new Error('Tenant ID is required');
    }
    return {
      tenantId: req.tenantId,
      userId: req.user?.sub,
    };
  };

  // ==================== Dashboard Endpoints (for frontend integration) ====================

  /**
   * GET /reports/dashboard/stats
   * Get aggregate dashboard statistics
   */
  router.get('/dashboard/stats', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const portfolio = await evmService.getPortfolioSummary(ctx);

      res.status(200).json({
        totalProyectos: portfolio.projects.length,
        proyectosActivos: portfolio.projects.filter(p => p.percentComplete < 100).length,
        presupuestoTotal: portfolio.totals.totalBac,
        avancePromedio: portfolio.projects.length > 0
          ? portfolio.projects.reduce((sum, p) => sum + p.percentComplete, 0) / portfolio.projects.length
          : 0,
        alertasActivas: portfolio.totals.projectsCritical + portfolio.totals.projectsAtRisk,
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/projects/summary
   * Get projects summary with KPIs
   */
  router.get('/projects/summary', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const status = req.query.status as string | undefined;
      const portfolio = await evmService.getPortfolioSummary(ctx);

      let items = portfolio.projects.map(p => ({
        id: p.fraccionamientoId,
        nombre: p.name,
        presupuesto: p.bac,
        avanceReal: p.percentComplete,
        avanceProgramado: p.percentComplete * (p.spi || 1), // Estimate planned progress
        spi: p.spi,
        cpi: p.cpi,
        status: p.status,
      }));

      // Filter by status if provided
      if (status) {
        items = items.filter(p => p.status === status);
      }

      res.status(200).json({
        items,
        total: items.length,
        page: 1,
        limit: items.length,
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/projects/:projectId/kpis
   * Get KPIs for a specific project
   */
  router.get('/projects/:projectId/kpis', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const { projectId } = req.params;
      const metrics = await evmService.getCurrentMetrics(ctx, projectId);

      res.status(200).json({
        ...metrics,
        date: metrics.date.toISOString(),
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/projects/:projectId/earned-value
   * Get Earned Value metrics for a project
   */
  router.get('/projects/:projectId/earned-value', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const { projectId } = req.params;
      const metrics = await evmService.getCurrentMetrics(ctx, projectId);

      res.status(200).json({
        ...metrics,
        date: metrics.date.toISOString(),
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/projects/:projectId/s-curve
   * Get S-Curve data for a project
   */
  router.get('/projects/:projectId/s-curve', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const { projectId } = req.params;
      const periodType = (req.query.periodType as 'daily' | 'weekly' | 'monthly') || 'weekly';

      const curvaS = await evmService.getCurvaS(ctx, projectId, { periodType });

      res.status(200).json(curvaS.map(point => ({
        date: point.date.toISOString(),
        plannedValue: point.pv,
        earnedValue: point.ev,
        actualCost: point.ac,
        plannedCumulative: point.pv,
        earnedCumulative: point.ev,
        actualCumulative: point.ac,
      })));
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/alerts
   * Get active alerts
   */
  router.get('/alerts', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const ctx = getContext(req);
      const acknowledged = req.query.acknowledged === 'true';

      // Get projects at risk or critical status as alerts
      const portfolio = await evmService.getPortfolioSummary(ctx);
      const alerts = portfolio.projects
        .filter(p => p.status !== 'green')
        .map((p, index) => ({
          id: `alert-${p.fraccionamientoId}-${index}`,
          projectId: p.fraccionamientoId,
          projectName: p.name,
          type: p.spi < p.cpi ? 'schedule' : 'cost',
          severity: p.status === 'red' ? 'critical' : 'warning',
          title: p.status === 'red'
            ? `Proyecto ${p.name} en estado crítico`
            : `Proyecto ${p.name} requiere atención`,
          message: p.spi < 0.95
            ? `SPI: ${p.spi.toFixed(2)} - Atraso en cronograma`
            : `CPI: ${p.cpi.toFixed(2)} - Desviación en costo`,
          metric: p.spi < p.cpi ? 'SPI' : 'CPI',
          value: p.spi < p.cpi ? p.spi : p.cpi,
          threshold: 0.95,
          createdAt: new Date().toISOString(),
        }));

      res.status(200).json({
        items: acknowledged ? [] : alerts,
        total: acknowledged ? 0 : alerts.length,
        page: 1,
        limit: alerts.length,
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /reports/alerts/:alertId/acknowledge
   * Acknowledge an alert
   */
  router.patch('/alerts/:alertId/acknowledge', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { alertId } = req.params;

      // For now, return success (alerts are derived from project status)
      res.status(200).json({
        id: alertId,
        acknowledgedAt: new Date().toISOString(),
        message: 'Alert acknowledged',
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /reports/alerts/:alertId/resolve
   * Resolve an alert
   */
  router.patch('/alerts/:alertId/resolve', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { alertId } = req.params;

      res.status(200).json({
        id: alertId,
        resolvedAt: new Date().toISOString(),
        message: 'Alert resolved',
      });
    } catch (error) {
      next(error);
    }
  });

  // ==================== Report Management Endpoints ====================

  /**
   * GET /reports
   * Listar reportes con filtros
   */
  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: ReportFilters = {};
      if (req.query.reportType) filters.reportType = req.query.reportType as any;
      if (req.query.isActive !== undefined) filters.isActive = req.query.isActive === 'true';
      if (req.query.isScheduled !== undefined) filters.isScheduled = req.query.isScheduled === 'true';
      if (req.query.search) filters.search = req.query.search as string;

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

  /**
   * GET /reports/scheduled
   * Obtener reportes programados
   */
  router.get('/scheduled', 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 reports = await reportService.findScheduled(getContext(req));
      res.status(200).json({ success: true, data: reports });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/type/:type
   * Obtener reportes por tipo
   */
  router.get('/type/:type', 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 reports = await reportService.findByType(getContext(req), req.params.type as any);
      res.status(200).json({ success: true, data: reports });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /reports/code/:code
   * Obtener reporte por código
   */
  router.get('/code/:code', 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 report = await reportService.findByCode(getContext(req), req.params.code);
      if (!report) {
        res.status(404).json({ error: 'Not Found', message: 'Report not found' });
        return;
      }

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

  /**
   * GET /reports/:id
   * Obtener reporte por 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 report = await reportService.findById(getContext(req), req.params.id);
      if (!report) {
        res.status(404).json({ error: 'Not Found', message: 'Report not found' });
        return;
      }

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

  /**
   * POST /reports
   * Crear reporte
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'analyst'), 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: CreateReportDto = req.body;
      if (!dto.code || !dto.name || !dto.reportType) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'code, name, and reportType are required',
        });
        return;
      }

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

  /**
   * PUT /reports/:id
   * Actualizar reporte
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'analyst'), 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: UpdateReportDto = req.body;
      const report = await reportService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * POST /reports/:id/execute
   * Ejecutar reporte
   */
  router.post('/:id/execute', 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 options: ExecuteReportDto = req.body;
      const execution = await reportService.executeReport(getContext(req), req.params.id, options);

      res.status(200).json({ success: true, data: execution });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Report not found') {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message === 'Report is not active') {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * GET /reports/:id/executions
   * Historial de ejecuciones
   */
  router.get('/:id/executions', 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 reportService.getExecutionHistory(getContext(req), req.params.id, 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 /reports/:id/executions/latest
   * Última ejecución
   */
  router.get('/:id/executions/latest', 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 execution = await reportService.getLastExecution(getContext(req), req.params.id);
      if (!execution) {
        res.status(404).json({ error: 'Not Found', message: 'No executions found' });
        return;
      }

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

  /**
   * GET /reports/executions/:executionId
   * Obtener ejecución específica
   */
  router.get('/executions/:executionId', 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 execution = await reportService.getExecution(getContext(req), req.params.executionId);
      if (!execution) {
        res.status(404).json({ error: 'Not Found', message: 'Execution not found' });
        return;
      }

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

  /**
   * DELETE /reports/:id
   * Eliminar reporte (soft delete)
   */
  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;
      }

      // Verificar que no sea un reporte de sistema
      const report = await reportService.findById(getContext(req), req.params.id);
      if (!report) {
        res.status(404).json({ error: 'Not Found', message: 'Report not found' });
        return;
      }

      if (report.isSystem) {
        res.status(403).json({ error: 'Forbidden', message: 'Cannot delete system reports' });
        return;
      }

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

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

  return router;
}

export default createReportController;
