// services/rabbitmqService.ts
import amqp, { Channel, ChannelModel } from "amqplib";

class RabbitmqService {
  /**
   * 将消息发布到指定的 RabbitMQ 队列
   * @param {string} queueName - 消息将要发送到的队列名称
   * @param {object} messagePayload - 要发送的 JSON 消息体
   */
  public async publishActivityMessage(queueName: string, messagePayload: object): Promise<void> {
    let connection: ChannelModel | null = null;
    try {
      const rabbitMqUrl = process.env.RABBITMQ_URL;
      if (!rabbitMqUrl) {
        throw new Error("RABBITMQ_URL not defined in environment variables.");
      }

      connection = await amqp.connect(rabbitMqUrl);
      const channel: Channel = await connection.createChannel();

      // 确保队列存在
      await channel.assertQueue(queueName, {
        durable: true,
      });

      // 将消息转换为 Buffer 并发送
      const msg = JSON.stringify(messagePayload);
      channel.sendToQueue(queueName, Buffer.from(msg), {
        persistent: true,
      });

      console.log(`[x] Sent message to queue '${queueName}': '${msg}'`);
    } catch (error) {
      if (error instanceof Error) {
        console.error(`Failed to publish message: ${error.message}`);
      } else {
        console.error("An unknown error occurred while publishing the message.");
      }
    } finally {
      if (connection) {
        // 确保连接在消息发送后关闭
        await connection.close();
      }
    }
  }
}

export default new RabbitmqService();
