"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const amqplib_1 = __importDefault(require("amqplib"));
const messageActivityService_1 = require("../src/services/messageActivityService");
// RabbitMQ连接URL，通常来自环境变量
const RABBITMQ_URL = process.env.RABBITMQ_URL || "amqp://coloring:coloring123.@localhost:5672";
// 消息队列的名称
const QUEUE_NAME = "message-record-generation-queue";
/**
 * 启动消息工作进程。
 * 该函数会连接到 RabbitMQ，监听消息队列，并处理每一条消息。
 */
const startWorker = async () => {
    try {
        // 建立与 RabbitMQ 的连接
        const connection = await amqplib_1.default.connect(RABBITMQ_URL);
        // 创建一个通道
        const channel = await connection.createChannel();
        // 声明消息队列，确保它存在
        await channel.assertQueue(QUEUE_NAME, { durable: true });
        console.log(" [*] Message worker is running and listening for messages in %s. To exit press CTRL+C", QUEUE_NAME);
        // 设置预取计数，一次只从队列中取出一条消息进行处理
        channel.prefetch(1);
        // 消费消息
        channel.consume(QUEUE_NAME, async (msg) => {
            if (msg !== null) {
                try {
                    const { activityId } = JSON.parse(msg.content.toString());
                    console.log(` [x] Received activityId: ${activityId}. Starting record generation...`);
                    // 使用 MessageActivityService 来生成记录
                    const service = new messageActivityService_1.MessageActivityService();
                    const count = await service.generateRecordsForActivity(activityId);
                    console.log(` [x] Finished processing activity ${activityId}. Generated ${count} records.`);
                    // 确认消息已处理，将其从队列中移除
                    channel.ack(msg);
                }
                catch (error) {
                    console.error(` [!] Error processing message: ${msg.content.toString()}`, error);
                    // 消息处理失败，将其拒绝并重新放回队列
                    channel.reject(msg, true);
                }
            }
        });
    }
    catch (error) {
        console.error("Failed to connect to RabbitMQ or start worker:", error);
        // 在这里可以实现重连逻辑，确保 worker 的健壮性
        setTimeout(startWorker, 5000); // 5秒后尝试重连
    }
};
startWorker();
