/**
 * [BE-SHOP-REP001] 多店铺报表聚合API路由
 * 提供多店铺报表的生成、查询、订阅接口
 */

import { Router } from 'express';
import { ShopReportAggregationService, ReportType, TimeDimension } from '../../services/ShopReportAggregationService';
import { logger } from '../../utils/logger';

const router = Router();

/**
 * POST /api/shop-reports/generate
 * 生成多店铺聚合报表
 */
router.post('/generate', async (req, res) => {
  try {
    const {
      tenant_id,
      report_type,
      time_dimension,
      start_date,
      end_date,
      shop_ids,
      platforms,
      regions,
    } = req.body;

    // 参数校验
    if (!tenant_id || !report_type || !time_dimension || !start_date || !end_date) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段: tenant_id, report_type, time_dimension, start_date, end_date',
      });
    }

    // 验证报表类型
    const validReportTypes: ReportType[] = ['SALES', 'PROFIT', 'INVENTORY', 'ORDER', 'AD', 'REFUND'];
    if (!validReportTypes.includes(report_type)) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_REPORT_TYPE',
        message: `报表类型必须是: ${validReportTypes.join(', ')}`,
      });
    }

    // 验证时间维度
    const validTimeDimensions: TimeDimension[] = ['DAILY', 'WEEKLY', 'MONTHLY', 'QUARTERLY', 'YEARLY'];
    if (!validTimeDimensions.includes(time_dimension)) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_TIME_DIMENSION',
        message: `时间维度必须是: ${validTimeDimensions.join(', ')}`,
      });
    }

    const report = await ShopReportAggregationService.generateReport({
      tenant_id,
      report_type,
      time_dimension,
      start_date,
      end_date,
      shop_ids,
      platforms,
      regions,
    });

    res.json({
      success: true,
      data: report,
      message: '报表生成成功',
    });
  } catch (error) {
    logger.error('[ShopReport] Generate report error:', error);
    const errorMessage = error instanceof Error ? error.message : '报表生成失败';
    res.status(500).json({
      success: false,
      error: 'GENERATE_REPORT_ERROR',
      message: errorMessage,
    });
  }
});

/**
 * POST /api/shop-reports/realtime
 * 实时聚合查询
 */
router.post('/realtime', async (req, res) => {
  try {
    const { tenant_id, shop_ids, metrics, start_date, end_date } = req.body;

    if (!tenant_id || !shop_ids || !metrics || !start_date || !end_date) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const results = await ShopReportAggregationService.realtimeAggregation({
      tenant_id,
      shop_ids,
      metrics,
      start_date,
      end_date,
    });

    res.json({
      success: true,
      data: results,
    });
  } catch (error) {
    logger.error('[ShopReport] Realtime aggregation error:', error);
    res.status(500).json({
      success: false,
      error: 'REALTIME_AGGREGATION_ERROR',
      message: '实时聚合查询失败',
    });
  }
});

/**
 * GET /api/shop-reports/history
 * 获取历史报表列表
 */
router.get('/history', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const reportType = req.query.report_type as ReportType;
    const limit = parseInt(req.query.limit as string) || 10;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_TENANT_ID',
        message: '缺少租户ID',
      });
    }

    const reports = await ShopReportAggregationService.getHistoricalReports(
      tenantId,
      reportType,
      limit
    );

    res.json({
      success: true,
      data: reports,
    });
  } catch (error) {
    logger.error('[ShopReport] Get history error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_HISTORY_ERROR',
      message: '获取历史报表失败',
    });
  }
});

/**
 * GET /api/shop-reports/:reportId
 * 获取报表详情
 */
router.get('/:reportId', async (req, res) => {
  try {
    const { reportId } = req.params;

    const report = await ShopReportAggregationService.getReportById(reportId);

    if (!report) {
      return res.status(404).json({
        success: false,
        error: 'REPORT_NOT_FOUND',
        message: '报表不存在',
      });
    }

    res.json({
      success: true,
      data: report,
    });
  } catch (error) {
    logger.error('[ShopReport] Get report error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_REPORT_ERROR',
      message: '获取报表失败',
    });
  }
});

/**
 * POST /api/shop-reports/subscriptions
 * 创建报表订阅
 */
router.post('/subscriptions', async (req, res) => {
  try {
    const {
      tenant_id,
      report_type,
      time_dimension,
      frequency,
      recipients,
    } = req.body;

    const userId = (req as any).user?.id;

    if (!tenant_id || !report_type || !time_dimension || !frequency || !recipients) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const subscription = await ShopReportAggregationService.createSubscription(
      tenant_id,
      userId,
      report_type,
      time_dimension,
      frequency,
      recipients
    );

    res.json({
      success: true,
      data: subscription,
      message: '订阅创建成功',
    });
  } catch (error) {
    logger.error('[ShopReport] Create subscription error:', error);
    res.status(500).json({
      success: false,
      error: 'CREATE_SUBSCRIPTION_ERROR',
      message: '创建订阅失败',
    });
  }
});

/**
 * GET /api/shop-reports/subscriptions/my
 * 获取当前用户的订阅列表
 */
router.get('/subscriptions/my', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    const userId = (req as any).user?.id;

    if (!tenantId || !userId) {
      return res.status(401).json({
        success: false,
        error: 'UNAUTHORIZED',
        message: '未登录',
      });
    }

    const subscriptions = await ShopReportAggregationService.getUserSubscriptions(
      tenantId,
      userId
    );

    res.json({
      success: true,
      data: subscriptions,
    });
  } catch (error) {
    logger.error('[ShopReport] Get subscriptions error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_SUBSCRIPTIONS_ERROR',
      message: '获取订阅列表失败',
    });
  }
});

/**
 * POST /api/shop-reports/init-tables
 * 初始化数据库表（仅管理员）
 */
router.post('/init-tables', async (req, res) => {
  try {
    const userRole = (req as any).user?.role;
    if (userRole !== 'ADMIN') {
      return res.status(403).json({
        success: false,
        error: 'FORBIDDEN',
        message: '只有管理员可以执行此操作',
      });
    }

    await ShopReportAggregationService.initTables();

    res.json({
      success: true,
      message: '数据库表初始化成功',
    });
  } catch (error) {
    logger.error('[ShopReport] Init tables error:', error);
    res.status(500).json({
      success: false,
      error: 'INIT_TABLES_ERROR',
      message: '初始化数据库表失败',
    });
  }
});

export default router;
