/**
 * EarnedValueController - Endpoints para Earned Value Management
 *
 * Expone métricas de Curva S, SPI, CPI para proyectos de construcción.
 *
 * @module Reports (Construction-specific)
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
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;
}

/**
 * Create the earned value controller with routes
 */
export function createEarnedValueController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const service = new EarnedValueService(dataSource);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

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

  /**
   * GET /earned-value/metrics/:fraccionamientoId
   * Get current EVM metrics for a project
   */
  router.get(
    '/metrics/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const asOfDate = req.query.asOfDate
          ? new Date(req.query.asOfDate as string)
          : undefined;

        const metrics = await service.getCurrentMetrics(ctx, fraccionamientoId, asOfDate);
        res.json(metrics);
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/curva-s/:fraccionamientoId
   * Get Curva S data for a project
   */
  router.get(
    '/curva-s/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const filters = {
          dateFrom: req.query.dateFrom
            ? new Date(req.query.dateFrom as string)
            : undefined,
          dateTo: req.query.dateTo
            ? new Date(req.query.dateTo as string)
            : undefined,
          periodType: (req.query.periodType as 'daily' | 'weekly' | 'monthly') || 'weekly',
        };

        const curvaS = await service.getCurvaS(ctx, fraccionamientoId, filters);
        res.json({
          fraccionamientoId,
          periodType: filters.periodType,
          dataPoints: curvaS.length,
          data: curvaS,
        });
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/spi/:fraccionamientoId
   * Get Schedule Performance Index for a project
   */
  router.get(
    '/spi/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const asOfDate = req.query.asOfDate
          ? new Date(req.query.asOfDate as string)
          : undefined;

        const spi = await service.calculateSPI(ctx, fraccionamientoId, asOfDate);
        res.json({
          fraccionamientoId,
          asOfDate: asOfDate || new Date(),
          ...spi,
        });
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/cpi/:fraccionamientoId
   * Get Cost Performance Index for a project
   */
  router.get(
    '/cpi/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const asOfDate = req.query.asOfDate
          ? new Date(req.query.asOfDate as string)
          : undefined;

        const cpi = await service.calculateCPI(ctx, fraccionamientoId, asOfDate);
        res.json({
          fraccionamientoId,
          asOfDate: asOfDate || new Date(),
          ...cpi,
        });
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/portfolio
   * Get EVM summary for all active projects
   */
  router.get(
    '/portfolio',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const fraccionamientoIds = req.query.fraccionamientoIds
          ? (req.query.fraccionamientoIds as string).split(',')
          : undefined;

        const summary = await service.getPortfolioSummary(ctx, fraccionamientoIds);
        res.json(summary);
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/trend/:fraccionamientoId
   * Get EVM trend over time for a project
   */
  router.get(
    '/trend/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const periodCount = req.query.periods
          ? parseInt(req.query.periods as string, 10)
          : 12;
        const periodType =
          (req.query.periodType as 'weekly' | 'monthly') || 'monthly';

        const trend = await service.getEvmTrend(ctx, fraccionamientoId, periodCount, periodType);
        res.json({
          fraccionamientoId,
          periodType,
          periodCount,
          trend,
        });
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * POST /earned-value/snapshot/:fraccionamientoId
   * Save current EVM metrics as KPI snapshot
   */
  router.post(
    '/snapshot/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;
        const asOfDate = req.body.asOfDate
          ? new Date(req.body.asOfDate)
          : undefined;

        await service.saveEvmSnapshot(ctx, fraccionamientoId, asOfDate);
        res.status(201).json({
          message: 'EVM snapshot saved successfully',
          fraccionamientoId,
          snapshotDate: asOfDate || new Date(),
        });
      } catch (error) {
        next(error);
      }
    }
  );

  /**
   * GET /earned-value/dashboard/:fraccionamientoId
   * Get comprehensive EVM dashboard data
   */
  router.get(
    '/dashboard/:fraccionamientoId',
    authMiddleware.authenticate,
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      try {
        const ctx = getContext(req);
        const { fraccionamientoId } = req.params;

        // Fetch all data in parallel
        const [metrics, curvaS, trend] = await Promise.all([
          service.getCurrentMetrics(ctx, fraccionamientoId),
          service.getCurvaS(ctx, fraccionamientoId, { periodType: 'weekly' }),
          service.getEvmTrend(ctx, fraccionamientoId, 6, 'monthly'),
        ]);

        res.json({
          fraccionamientoId,
          currentMetrics: metrics,
          curvaS,
          trend,
          summary: {
            percentComplete: metrics.percentComplete,
            spi: metrics.spi,
            cpi: metrics.cpi,
            status: metrics.status,
            projectedCompletion: metrics.eac,
            variance: metrics.vac,
          },
        });
      } catch (error) {
        next(error);
      }
    }
  );

  return router;
}
