const { validationResult } = require('express-validator');
const AdminStatisticsService = require('../services/adminStatisticsService');
const logger = require('../config/logger');

/**
 * Admin Statistics Controller
 * Handles statistical analysis and reporting endpoints
 */
class AdminStatisticsController {
  /**
   * Get comprehensive statistics data
   * @route GET /api/v1/admin/statistics
   */
  static async getStatistics(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate, groupBy = 'day', serviceLimit = 10 } = req.query;

      const statistics = await AdminStatisticsService.getStatistics({
        startDate,
        endDate,
        groupBy,
        serviceLimit: parseInt(serviceLimit),
      });

      res.json({
        success: true,
        data: statistics,
      });
    } catch (error) {
      logger.error('Error in getStatistics:', error);
      next(error);
    }
  }

  /**
   * Get dashboard metrics only
   * @route GET /api/v1/admin/statistics/dashboard
   */
  static async getDashboardMetrics(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate } = req.query;

      const metrics = await AdminStatisticsService.getDashboardMetrics({
        startDate,
        endDate,
      });

      res.json({
        success: true,
        data: metrics,
      });
    } catch (error) {
      logger.error('Error in getDashboardMetrics:', error);
      next(error);
    }
  }

  /**
   * Get user growth trends
   * @route GET /api/v1/admin/statistics/user-growth
   */
  static async getUserGrowthTrends(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate, groupBy = 'day' } = req.query;

      const trends = await AdminStatisticsService.getUserGrowthTrends({
        startDate,
        endDate,
        groupBy,
      });

      res.json({
        success: true,
        data: trends,
      });
    } catch (error) {
      logger.error('Error in getUserGrowthTrends:', error);
      next(error);
    }
  }

  /**
   * Get service popularity rankings
   * @route GET /api/v1/admin/statistics/service-rankings
   */
  static async getServicePopularityRankings(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate, limit = 10 } = req.query;

      const rankings = await AdminStatisticsService.getServicePopularityRankings({
        startDate,
        endDate,
        limit: parseInt(limit),
      });

      res.json({
        success: true,
        data: rankings,
      });
    } catch (error) {
      logger.error('Error in getServicePopularityRankings:', error);
      next(error);
    }
  }

  /**
   * Get invitation conversion rate
   * @route GET /api/v1/admin/statistics/invitation-conversion
   */
  static async getInvitationConversionRate(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate } = req.query;

      const conversionData = await AdminStatisticsService.getInvitationConversionRate({
        startDate,
        endDate,
      });

      res.json({
        success: true,
        data: conversionData,
      });
    } catch (error) {
      logger.error('Error in getInvitationConversionRate:', error);
      next(error);
    }
  }

  /**
   * Get financial report
   * @route GET /api/v1/admin/statistics/financial-report
   */
  static async getFinancialReport(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { startDate, endDate } = req.query;

      const report = await AdminStatisticsService.getFinancialReport({
        startDate,
        endDate,
      });

      res.json({
        success: true,
        data: report,
      });
    } catch (error) {
      logger.error('Error in getFinancialReport:', error);
      next(error);
    }
  }
}

module.exports = AdminStatisticsController;
