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

/**
 * 初始化所有 DoneRate 历史文档中缺失的 tipCount 字段为 0。
 * 确保所有文档在开始回填前拥有 tipCount 字段，以保证数据一致性。
 * @returns Promise<string> - 返回初始化结果的摘要信息。
 */
export async function runInitialization(): Promise<string> {
  console.log("[TipCount Initialization] Starting to set missing tipCount field to 0 for all historical DoneRate documents...");
  const startTime = Date.now();

  try {
    // 查找条件: 查找 tipCount 字段不存在的文档 (即历史数据)
    const filter = { tipCount: { $exists: false } };
    // 更新操作: 将 tipCount 设置为 0
    const update = { $set: { tipCount: 0 } };
    // 选项: 更新所有匹配的文档
    const options = { multi: true };

    const result = await DoneRate.updateMany(filter, update, options).exec();

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

    if (result.modifiedCount === 0) {
      console.log("[TipCount Initialization] No missing tipCount fields found. Historical data seems consistent or already initialized.");
    } else {
      console.log(`[TipCount Initialization] Successfully initialized ${result.modifiedCount} historical DoneRate documents to tipCount: 0.`);
    }

    const summary = `[TipCount Initialization] Initialization completed in ${timeTaken} seconds. Total documents modified: ${result.modifiedCount}.`;
    console.log(`\n${summary}`);
    return summary;
  } catch (error) {
    console.error("[TipCount Initialization] Fatal error during initialization:", error);
    throw new Error("Failed to initialize DoneRate tipCount field.");
  }
}
