/**
 * 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 { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Report } from '../entities/report.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';
import { ServiceContext } from '../../../shared/services/base.service';

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

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

  // Servicios
  const reportService = new ReportService(reportRepository, 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,
    };
  };

  /**
   * 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: result.meta,
      });
    } 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: result.meta,
      });
    } 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;
