/**
 * KpiController - Controller de KPIs
 *
 * Endpoints REST para gestión de KPIs y analytics.
 *
 * @module Reports
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { KpiService, CreateKpiSnapshotDto, KpiFilters } from '../services/kpi.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 createKpiController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const kpiService = new KpiService(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 /kpis
   * Listar snapshots de KPIs 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: KpiFilters = {};
      if (req.query.kpiCode) filters.kpiCode = req.query.kpiCode as string;
      if (req.query.category) filters.category = req.query.category as any;
      if (req.query.periodType) filters.periodType = req.query.periodType as any;
      if (req.query.fraccionamientoId) filters.fraccionamientoId = req.query.fraccionamientoId as string;
      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 kpiService.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 /kpis/stats
   * Estadísticas de KPIs
   */
  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 kpiService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /kpis/dashboard
   * KPIs para dashboard agrupados por categoría
   */
  router.get('/dashboard', 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 fraccionamientoId = req.query.fraccionamientoId as string | undefined;
      const dashboard = await kpiService.getDashboardKpis(getContext(req), fraccionamientoId);

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

  /**
   * GET /kpis/category/:category
   * Resumen de KPIs por categoría
   */
  router.get('/category/:category', 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 fraccionamientoId = req.query.fraccionamientoId as string | undefined;
      const summary = await kpiService.getSummaryByCategory(
        getContext(req),
        req.params.category as any,
        fraccionamientoId
      );

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

  /**
   * GET /kpis/code/:code/latest
   * Último snapshot de un KPI
   */
  router.get('/code/:code/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 fraccionamientoId = req.query.fraccionamientoId as string | undefined;
      const snapshot = await kpiService.getLatestSnapshot(
        getContext(req),
        req.params.code,
        fraccionamientoId
      );

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

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

  /**
   * GET /kpis/code/:code/trend
   * Tendencia de un KPI
   */
  router.get('/code/:code/trend', 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 days = parseInt(req.query.days as string) || 30;
      const fraccionamientoId = req.query.fraccionamientoId as string | undefined;

      const trend = await kpiService.getKpiTrend(
        getContext(req),
        req.params.code,
        days,
        fraccionamientoId
      );

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

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

  /**
   * GET /kpis/code/:code/history
   * Historial de un KPI
   */
  router.get('/code/:code/history', 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 dateFrom = req.query.dateFrom ? new Date(req.query.dateFrom as string) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
      const dateTo = req.query.dateTo ? new Date(req.query.dateTo as string) : new Date();
      const fraccionamientoId = req.query.fraccionamientoId as string | undefined;

      const history = await kpiService.getKpiHistory(
        getContext(req),
        req.params.code,
        dateFrom,
        dateTo,
        fraccionamientoId
      );

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

  /**
   * GET /kpis/code/:code/compare
   * Comparar KPI entre proyectos
   */
  router.get('/code/:code/compare', 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 fraccionamientoIds = (req.query.fraccionamientoIds as string)?.split(',') || [];
      if (fraccionamientoIds.length < 2) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'At least 2 fraccionamientoIds are required for comparison',
        });
        return;
      }

      const snapshotDate = req.query.date ? new Date(req.query.date as string) : undefined;
      const comparison = await kpiService.compareProjects(
        getContext(req),
        req.params.code,
        fraccionamientoIds,
        snapshotDate
      );

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

  /**
   * POST /kpis
   * Crear snapshot de KPI
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'analyst', 'system'), 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: CreateKpiSnapshotDto = req.body;
      if (!dto.kpiCode || !dto.kpiName || !dto.category || !dto.snapshotDate || dto.value === undefined) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'kpiCode, kpiName, category, snapshotDate, and value are required',
        });
        return;
      }

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

  /**
   * POST /kpis/bulk
   * Crear múltiples snapshots (para jobs)
   */
  router.post('/bulk', authMiddleware.authenticate, authMiddleware.authorize('admin', 'system'), 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 { snapshots } = req.body;
      if (!Array.isArray(snapshots) || snapshots.length === 0) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'snapshots array is required and must not be empty',
        });
        return;
      }

      const result = await kpiService.bulkCreateSnapshots(getContext(req), snapshots);
      res.status(201).json({
        success: true,
        data: result,
        message: `Created ${result.created} snapshots, ${result.errors} errors`,
      });
    } catch (error) {
      next(error);
    }
  });

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

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

  return router;
}

export default createKpiController;
