import mongoose from "mongoose";
import DoneRate from "../models/doneRateModel";
import TotalDoneRate from "../models/totalDoneRateModel";

/**
 * 重新计算 TotalDoneRate 表中的所有累计字段。
 * 通过聚合 DoneRate 表中的所有历史数据来实现。
 * 此脚本应在 DoneRate 表的 tipCount 字段回填完成后运行。
 * @returns Promise<string> - 返回累计更新结果的摘要信息。
 */
export async function runRecalculation(): Promise<string> {
  console.log("[TotalDoneRate Recalculation] Starting full recalculation of TotalDoneRate table...");
  const startTime = Date.now();

  try {
    // 1. 使用聚合操作，从 DoneRate 表中计算每个作品的总累计数据
    console.log("[TotalDoneRate Recalculation] Step 1: Aggregating all DoneRate records...");

    // 聚合管道定义
    const aggregationPipeline = [
      {
        // 1. 按作品 ID (res) 分组
        $group: {
          _id: "$res", // 使用 res 作为分组键
          totalStartCount: { $sum: "$startCount" },
          totalDoneCount: { $sum: "$doneCount" },
          totalTipCount: { $sum: "$tipCount" }, // 累加 tipCount
        },
      },
      {
        // 2. 计算最终的 completionRate
        $project: {
          _id: "$_id",
          totalStartCount: "$totalStartCount",
          totalDoneCount: "$totalDoneCount",
          totalTipCount: "$totalTipCount",
          completionRate: {
            $cond: [
              { $gt: ["$totalStartCount", 0] },
              { $multiply: [{ $divide: ["$totalDoneCount", "$totalStartCount"] }, 100] },
              0, // 如果 totalStartCount 为 0，则 completionRate 为 0
            ],
          },
        },
      },
    ];

    const aggregatedResults = await DoneRate.aggregate(aggregationPipeline).exec();

    console.log(`[TotalDoneRate Recalculation] Aggregation complete. Found ${aggregatedResults.length} unique artworks to update.`);

    // 2. 批量更新 TotalDoneRate 表
    const bulkOps = aggregatedResults.map((result) => ({
      updateOne: {
        // 查找条件：使用聚合结果的 _id (即作品 ObjectId)
        filter: { _id: result._id },
        // 更新操作：设置所有累计字段
        update: {
          $set: {
            totalStartCount: result.totalStartCount,
            totalDoneCount: result.totalDoneCount,
            totalTipCount: result.totalTipCount, // 设置重新计算的总道具使用数
            completionRate: result.completionRate,
          },
        },
        // 如果 TotalDoneRate 记录不存在，则创建新记录
        upsert: true,
      },
    }));

    if (bulkOps.length > 0) {
      console.log(`[TotalDoneRate Recalculation] Step 2: Running bulk update for ${bulkOps.length} documents...`);
      const updateResult = await TotalDoneRate.bulkWrite(bulkOps, { ordered: false });

      const modifiedCount = (updateResult.modifiedCount || 0) + (updateResult.upsertedCount || 0);

      const endTime = Date.now();
      const timeTaken = ((endTime - startTime) / 1000).toFixed(2);

      const summary = `[TotalDoneRate Recalculation] Full recalculation completed in ${timeTaken} seconds. Total artworks updated/created: ${modifiedCount}.`;
      console.log(`\n${summary}`);
      return summary;
    } else {
      const summary = "[TotalDoneRate Recalculation] Aggregation returned no results. TotalDoneRate table update skipped.";
      console.log(summary);
      return summary;
    }
  } catch (error) {
    console.error("[TotalDoneRate Recalculation] Fatal error during full recalculation:", error);
    throw new Error("Failed to recalculate TotalDoneRate history.");
  }
}
