import { Router, Request, Response } from 'express';
import LeaderboardService from '../../services/LeaderboardService';
import MerchantMetricsService from '../../services/MerchantMetricsService';
import { logger } from '../../utils/logger';

const router = Router();

router.get('/leaderboard/:type', async (req: Request, res: Response) => {
  try {
    const type = req.params.type as string;
    const period = (req.query.period as 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'ALL_TIME') || 'MONTHLY';
    const limit = parseInt(req.query.limit as string) || 10;

    if (!['REVENUE', 'ROI', 'GROWTH'].includes(type)) {
      return res.status(400).json({
        success: false,
        message: 'Invalid leaderboard type. Must be REVENUE, ROI, or GROWTH'
      });
    }

    const leaderboard = await LeaderboardService.getLeaderboard(
      type as 'REVENUE' | 'ROI' | 'GROWTH',
      period
    );

    res.json({
      success: true,
      data: {
        type,
        period,
        rankings: leaderboard.slice(0, limit),
        total: leaderboard.length,
        updatedAt: new Date().toISOString()
      }
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching leaderboard:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch leaderboard'
    });
  }
});

router.get('/leaderboard/all', async (req: Request, res: Response) => {
  try {
    const period = (req.query.period as 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'ALL_TIME') || 'MONTHLY';

    const [revenue, roi, growth] = await Promise.all([
      LeaderboardService.getLeaderboard('REVENUE', period),
      LeaderboardService.getLeaderboard('ROI', period),
      LeaderboardService.getLeaderboard('GROWTH', period)
    ]);

    res.json({
      success: true,
      data: {
        revenue: { rankings: revenue, total: revenue.length },
        roi: { rankings: roi, total: roi.length },
        growth: { rankings: growth, total: growth.length },
        period,
        updatedAt: new Date().toISOString()
      }
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching all leaderboards:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch leaderboards'
    });
  }
});

router.get('/leaderboard/stats', async (req: Request, res: Response) => {
  try {
    const stats = await LeaderboardService.getLeaderboardStats();

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching leaderboard stats:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch leaderboard stats'
    });
  }
});

router.get('/leaderboard/my-rank', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const period = (req.query.period as 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'ALL_TIME') || 'MONTHLY';

    const [revenueRank, roiRank, growthRank] = await Promise.all([
      LeaderboardService.getMerchantRank(tenantId, 'REVENUE', period),
      LeaderboardService.getMerchantRank(tenantId, 'ROI', period),
      LeaderboardService.getMerchantRank(tenantId, 'GROWTH', period)
    ]);

    res.json({
      success: true,
      data: {
        revenue: revenueRank,
        roi: roiRank,
        growth: growthRank,
        period
      }
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching merchant rank:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch merchant rank'
    });
  }
});

router.get('/metrics/my-metrics', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const metrics = await MerchantMetricsService.getLatestMetrics(tenantId);

    res.json({
      success: true,
      data: metrics
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching merchant metrics:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch merchant metrics'
    });
  }
});

router.get('/metrics/history', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const startDate = req.query.startDate 
      ? new Date(req.query.startDate as string)
      : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const endDate = req.query.endDate 
      ? new Date(req.query.endDate as string)
      : new Date();

    const history = await MerchantMetricsService.getMetricsHistory(tenantId, startDate, endDate);

    res.json({
      success: true,
      data: {
        history,
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString()
      }
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching metrics history:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch metrics history'
    });
  }
});

router.post('/metrics/calculate', async (req: Request, res: Response) => {
  try {
    const { tenantId, shopId, period = 'MONTHLY' } = req.body;

    if (!tenantId || !shopId) {
      return res.status(400).json({
        success: false,
        message: 'tenantId and shopId are required'
      });
    }

    const metrics = await MerchantMetricsService.calculateAndStoreMetrics({
      tenantId,
      shopId,
      period
    });

    res.json({
      success: true,
      data: metrics,
      message: 'Metrics calculated and stored successfully'
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error calculating metrics:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to calculate metrics'
    });
  }
});

router.post('/leaderboard/refresh', async (req: Request, res: Response) => {
  try {
    const { type, period } = req.body;

    if (type && period) {
      await LeaderboardService.refreshLeaderboard(type, period);
      res.json({
        success: true,
        message: `Leaderboard ${type} - ${period} refreshed successfully`
      });
    } else {
      await LeaderboardService.refreshAllLeaderboards();
      res.json({
        success: true,
        message: 'All leaderboards refreshed successfully'
      });
    }
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error refreshing leaderboard:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to refresh leaderboard'
    });
  }
});

router.post('/metrics/verify/:metricsId', async (req: Request, res: Response) => {
  try {
    const metricsId = req.params.metricsId as string;

    await MerchantMetricsService.verifyMetrics(metricsId);

    res.json({
      success: true,
      message: 'Metrics verified successfully'
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error verifying metrics:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to verify metrics'
    });
  }
});

router.get('/metrics/suspicious', async (req: Request, res: Response) => {
  try {
    const suspicious = await MerchantMetricsService.flagSuspiciousMetrics();

    res.json({
      success: true,
      data: suspicious,
      message: `Found ${suspicious.length} potentially suspicious metrics`
    });
  } catch (error) {
    logger.error('[LeaderboardRoutes] Error fetching suspicious metrics:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch suspicious metrics'
    });
  }
});

export default router;
