/**
 * 内部 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';
import { wsManager } from '../websocket/index.js';
import { WS_EVENTS } from '@media-manager/shared';
import { AppDataSource, PlatformAccount, Work } from '../models/index.js';
import { CookieManager } from '../automation/cookie.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,
      exposureCount:
        item.exposureCount ??
        item.exposure_count ??
        item.impressionCount ??
        item.impression_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,
      fansIncrease:
        item.fansIncrease ??
        item.fans_increase ??
        item.riseFansCount ??
        item.rise_fans_count ??
        0,
      coverClickRate: item.coverClickRate ?? item.cover_click_rate,
      avgWatchDuration: item.avgWatchDuration ?? item.avg_watch_duration,
      totalWatchDuration: item.totalWatchDuration ?? item.total_watch_duration ?? '0',
      completionRate: item.completionRate ?? item.completion_rate ?? item.finish_rate ?? item.full_view_rate,
      twoSecondExitRate: item.twoSecondExitRate ?? item.two_second_exit_rate ?? item.exit_view2s_rate,
    }));

    const result = await workDayStatisticsService.saveStatistics(statistics);

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

/**
 * POST /api/internal/work-day-statistics/batch-dates
 * 按日期批量保存作品日统计数据（用于视频号 CSV 导入等）
 */
router.post(
  '/work-day-statistics/batch-dates',
  [
    body('statistics').isArray().withMessage('statistics 必须是数组'),
    body('statistics.*.workId').optional().isNumeric().withMessage('workId 必须是数字'),
    body('statistics.*.work_id').optional().isNumeric().withMessage('work_id 必须是数字'),
    body('statistics.*.recordDate').optional().isString().withMessage('recordDate 必须是字符串'),
    body('statistics.*.record_date').optional().isString().withMessage('record_date 必须是字符串'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const items = req.body.statistics.map((item: any) => {
      const workId = item.workId ?? item.work_id;
      const recordDateStr = item.recordDate ?? item.record_date ?? '';
      const recordDate = recordDateStr ? new Date(recordDateStr) : new Date();
      recordDate.setHours(0, 0, 0, 0);
      return {
        workId: Number(workId),
        recordDate,
        playCount: item.playCount ?? item.play_count ?? 0,
        exposureCount: item.exposureCount ?? item.exposure_count ?? 0,
        likeCount: item.likeCount ?? item.like_count ?? 0,
        recommendCount: item.recommendCount ?? item.recommend_count ?? 0,
        commentCount: item.commentCount ?? item.comment_count ?? 0,
        shareCount: item.shareCount ?? item.share_count ?? 0,
        collectCount: item.collectCount ?? item.collect_count ?? 0,
        fansIncrease: item.fansIncrease ?? item.fans_increase ?? 0,
        followCount: item.followCount ?? item.follow_count ?? 0,
        coverClickRate: String(item.coverClickRate ?? item.cover_click_rate ?? '0'),
        avgWatchDuration: String(item.avgWatchDuration ?? item.avg_watch_duration ?? '0'),
        totalWatchDuration: String(item.totalWatchDuration ?? item.total_watch_duration ?? '0'),
        completionRate: String(item.completionRate ?? item.completion_rate ?? '0'),
        twoSecondExitRate: String(item.twoSecondExitRate ?? item.two_second_exit_rate ?? '0'),
      };
    });

    const result = await workDayStatisticsService.saveStatisticsForDateBatch(items);

    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,
    });
  })
);

/**
 * POST /api/internal/works/batch-update-from-csv
 * 根据视频号 CSV 明细批量更新 works 表 yesterday_* 字段
 * 请求体: { "updates": [{ work_id, yesterday_play_count, yesterday_like_count, yesterday_comment_count, yesterday_share_count, yesterday_completion_rate, yesterday_avg_watch_duration }, ...] }
 */
router.post(
  '/works/batch-update-from-csv',
  [
    body('updates').isArray().withMessage('updates 必须是数组'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const raw = req.body.updates as Array<any>;
    const updates = raw
      .map((item) => ({
        work_id: item.work_id ?? item.workId,
        yesterday_play_count: item.yesterday_play_count ?? item.yesterdayPlayCount,
        yesterday_like_count: item.yesterday_like_count ?? item.yesterdayLikeCount,
        yesterday_recommend_count: item.yesterday_recommend_count ?? item.yesterdayRecommendCount,
        yesterday_comment_count: item.yesterday_comment_count ?? item.yesterdayCommentCount,
        yesterday_share_count: item.yesterday_share_count ?? item.yesterdayShareCount,
        yesterday_follow_count: item.yesterday_follow_count ?? item.yesterdayFollowCount,
        yesterday_completion_rate: item.yesterday_completion_rate ?? item.yesterdayCompletionRate,
        yesterday_avg_watch_duration: item.yesterday_avg_watch_duration ?? item.yesterdayAvgWatchDuration,
      }))
      .filter((item) => item.work_id != null);

    const workRepository = AppDataSource.getRepository(Work);
    let updated = 0;
    for (const item of updates) {
      const patch: Partial<{
        yesterdayPlayCount: number;
        yesterdayLikeCount: number;
        yesterdayRecommendCount: number;
        yesterdayCommentCount: number;
        yesterdayShareCount: number;
        yesterdayFollowCount: number;
        yesterdayCompletionRate: string;
        yesterdayAvgWatchDuration: string;
      }> = {};
      if (item.yesterday_play_count !== undefined) patch.yesterdayPlayCount = item.yesterday_play_count;
      if (item.yesterday_like_count !== undefined) patch.yesterdayLikeCount = item.yesterday_like_count;
      if (item.yesterday_recommend_count !== undefined) patch.yesterdayRecommendCount = item.yesterday_recommend_count;
      if (item.yesterday_comment_count !== undefined) patch.yesterdayCommentCount = item.yesterday_comment_count;
      if (item.yesterday_share_count !== undefined) patch.yesterdayShareCount = item.yesterday_share_count;
      if (item.yesterday_follow_count !== undefined) patch.yesterdayFollowCount = item.yesterday_follow_count;
      if (item.yesterday_completion_rate !== undefined) patch.yesterdayCompletionRate = String(item.yesterday_completion_rate);
      if (item.yesterday_avg_watch_duration !== undefined) patch.yesterdayAvgWatchDuration = String(item.yesterday_avg_watch_duration);
      if (Object.keys(patch).length === 0) continue;

      const result = await workRepository.update(item.work_id, patch);
      if (result.affected && result.affected > 0) updated += result.affected;
    }

    res.json({
      success: true,
      updated,
      message: `成功更新 ${updated} 条 works 记录`,
    });
  })
);

/**
 * POST /api/internal/captcha/request
 * Python 发布服务请求前端输入验证码（短信/图形）
 */
router.post(
  '/captcha/request',
  [
    body('user_id').isInt().withMessage('user_id 必须是整数'),
    body('captcha_task_id').notEmpty().withMessage('captcha_task_id 不能为空'),
    body('type').isIn(['sms', 'image']).withMessage('type 必须是 sms 或 image'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const userId = Number(req.body.user_id);
    const captchaTaskId = String(req.body.captcha_task_id);
    const type = req.body.type as 'sms' | 'image';
    const phone = (req.body.phone ? String(req.body.phone) : '') || '';
    const imageBase64 = (req.body.image_base64 ? String(req.body.image_base64) : '') || '';
    const message = (req.body.message ? String(req.body.message) : '') || '';

    const code = await new Promise<string>((resolve, reject) => {
      wsManager.sendToUser(userId, WS_EVENTS.CAPTCHA_REQUIRED, {
        captchaTaskId,
        type,
        phone,
        imageBase64,
        message,
      });

      const timeout = setTimeout(() => {
        wsManager.removeCaptchaListener(captchaTaskId);
        reject(new Error('验证码输入超时'));
      }, 120000);

      wsManager.onCaptchaSubmit(captchaTaskId, (captchaCode: string) => {
        clearTimeout(timeout);
        wsManager.removeCaptchaListener(captchaTaskId);
        if (!captchaCode) {
          reject(new Error('验证码已取消'));
          return;
        }
        resolve(captchaCode);
      });
    });

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

/**
 * POST /api/internal/accounts/update-cookies
 * Python 发布服务回写账号 Cookie（例如：有头浏览器手动登录后）
 */
router.post(
  '/accounts/update-cookies',
  [
    body('user_id').isInt().withMessage('user_id 必须是整数'),
    body('account_id').isInt().withMessage('account_id 必须是整数'),
    body('cookies').notEmpty().withMessage('cookies 不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const userId = Number(req.body.user_id);
    const accountId = Number(req.body.account_id);
    const cookies = String(req.body.cookies || '');

    const accountRepository = AppDataSource.getRepository(PlatformAccount);
    const account = await accountRepository.findOne({ where: { id: accountId, userId } });
    if (!account) {
      return res.status(404).json({ success: false, error: '账号不存在' });
    }

    const encrypted = CookieManager.encrypt(cookies);
    await accountRepository.update(accountId, {
      cookieData: encrypted,
      status: 'active',
      updatedAt: new Date(),
    });

    const updated = await accountRepository.findOne({ where: { id: accountId } });
    wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: updated });

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

export default router;
