/**
 * 内部 API 路由
 * 供 Python 服务调用，不需要用户认证
 * 但需要内部 API 密钥验证
 */
import { Router, Request, Response, NextFunction } from 'express';
import { body, query } from 'express-validator';
import { WorkDayStatisticsService } from '../services/WorkDayStatisticsService.js';
import { asyncHandler } from '../middleware/error.js';
import { validateRequest } from '../middleware/validate.js';
import { config } from '../config/index.js';

const router = Router();
const workDayStatisticsService = new WorkDayStatisticsService();

// 内部 API 密钥验证中间件
const validateInternalApiKey = (req: Request, res: Response, next: NextFunction) => {
  const apiKey = req.headers['x-internal-api-key'] as string;
  const expectedKey = config.internalApiKey || 'internal-api-key-default';
  
  if (!apiKey || apiKey !== expectedKey) {
    return res.status(401).json({
      success: false,
      error: 'Invalid internal API key',
    });
  }
  
  next();
};

// 应用内部 API 密钥验证
router.use(validateInternalApiKey);

/**
 * POST /api/internal/work-day-statistics
 * 保存作品日统计数据
 */
router.post(
  '/work-day-statistics',
  [
    body('statistics').isArray().withMessage('statistics 必须是数组'),
    body('statistics.*.workId').optional().isNumeric().withMessage('workId 必须是数字'),
    body('statistics.*.work_id').optional().isNumeric().withMessage('work_id 必须是数字'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    // 兼容 Python 传过来的下划线命名
    const statistics = req.body.statistics.map((item: any) => ({
      workId: item.workId ?? item.work_id,
      fansCount: item.fansCount ?? item.fans_count ?? 0,
      playCount: item.playCount ?? item.play_count ?? 0,
      likeCount: item.likeCount ?? item.like_count ?? 0,
      commentCount: item.commentCount ?? item.comment_count ?? 0,
      shareCount: item.shareCount ?? item.share_count ?? 0,
      collectCount: item.collectCount ?? item.collect_count ?? 0,
    }));

    const result = await workDayStatisticsService.saveStatistics(statistics);

    res.json({
      success: true,
      inserted: result.inserted,
      updated: result.updated,
      message: `保存成功: 新增 ${result.inserted} 条, 更新 ${result.updated} 条`,
    });
  })
);

/**
 * GET /api/internal/work-day-statistics/trend
 * 获取数据趋势
 */
router.get(
  '/work-day-statistics/trend',
  [
    query('user_id').notEmpty().withMessage('user_id 不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const userId = parseInt(req.query.user_id as string);
    const days = req.query.days ? parseInt(req.query.days as string) : undefined;
    const startDate = req.query.start_date as string | undefined;
    const endDate = req.query.end_date as string | undefined;
    const accountId = req.query.account_id ? parseInt(req.query.account_id as string) : undefined;

    const data = await workDayStatisticsService.getTrend(userId, {
      days,
      startDate,
      endDate,
      accountId,
    });

    res.json({
      success: true,
      data,
    });
  })
);

/**
 * GET /api/internal/work-day-statistics/platforms
 * 按平台分组获取统计数据
 */
router.get(
  '/work-day-statistics/platforms',
  [
    query('user_id').notEmpty().withMessage('user_id 不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const userId = parseInt(req.query.user_id as string);
    const days = req.query.days ? parseInt(req.query.days as string) : undefined;
    const startDate = req.query.start_date as string | undefined;
    const endDate = req.query.end_date as string | undefined;

    const data = await workDayStatisticsService.getStatisticsByPlatform(userId, {
      days,
      startDate,
      endDate,
    });

    res.json({
      success: true,
      data,
    });
  })
);

/**
 * POST /api/internal/work-day-statistics/batch
 * 批量获取作品的历史统计数据
 */
router.post(
  '/work-day-statistics/batch',
  [
    body('work_ids').isArray().withMessage('work_ids 必须是数组'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const workIds = req.body.work_ids;
    const startDate = req.body.start_date as string | undefined;
    const endDate = req.body.end_date as string | undefined;

    const data = await workDayStatisticsService.getWorkStatisticsHistory(workIds, {
      startDate,
      endDate,
    });

    res.json({
      success: true,
      data,
    });
  })
);

/**
 * GET /api/internal/work-day-statistics/overview
 * 获取数据总览（账号列表和汇总统计）
 */
router.get(
  '/work-day-statistics/overview',
  [
    query('user_id').notEmpty().withMessage('user_id 不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const userId = parseInt(req.query.user_id as string);
    const data = await workDayStatisticsService.getOverview(userId);

    res.json({
      success: true,
      data,
    });
  })
);

export default router;
