import { Router } from 'express';
import { ShopReportAggregationService, ReportType, TimeGranularity } from '../../services/analytics/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) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const context = { 
      tenantId: tenant_id,
      userId: 'system',
      role: 'ADMIN',
      permissions: ['*'],
      hierarchyPath: '/'
    };
    const query = {
      tenantId: tenant_id,
      dateFrom: start_date,
      dateTo: end_date,
      shopIds: shop_ids,
      platforms,
      regions,
      granularity: time_dimension,
    };

    let report;
    switch (report_type) {
      case 'SALES':
        report = await ShopReportAggregationService.getSalesReport(context, query);
        break;
      case 'PROFIT':
        report = await ShopReportAggregationService.getProfitReport(context, query);
        break;
      case 'INVENTORY':
        report = await ShopReportAggregationService.getInventoryReport(context, query);
        break;
      default:
        return res.status(400).json({
          success: false,
          error: 'INVALID_REPORT_TYPE',
          message: '不支持的报表类型',
        });
    }

    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/export
 * 导出报表
 */
router.post('/export', async (req, res) => {
  try {
    const { reportId, format, tenantId } = req.body;

    if (!reportId || !format || !tenantId) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const result = await ShopReportAggregationService.exportReport(
      { 
        tenantId,
        userId: 'system',
        role: 'ADMIN',
        permissions: ['*'],
        hierarchyPath: '/'
      },
      reportId,
      format
    );

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

/**
 * DELETE /api/shop-reports/cache/:tenantId
 * 清除报表缓存
 */
router.delete('/cache/:tenantId', async (req, res) => {
  try {
    const { tenantId } = req.params;

    await ShopReportAggregationService.clearReportCache(tenantId);

    res.json({
      success: true,
      message: '报表缓存清除成功',
    });
  } catch (error) {
    logger.error('[ShopReport] Clear cache error:', error);
    const errorMessage = error instanceof Error ? error.message : '报表缓存清除失败';
    res.status(500).json({
      success: false,
      error: 'CLEAR_CACHE_ERROR',
      message: errorMessage,
    });
  }
});

export default router;
