"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const messageActivityModel_1 = require("../models/messageActivityModel");
const rabbitmqService_1 = __importDefault(require("../services/rabbitmqService"));
const QUEUE_NAME = "message-record-generation-queue";
class MessageActivityController {
    /**
     * @route POST /api/message-activity
     * @desc 创建一个新的消息活动
     * @access Private
     */
    async createActivity(req, res) {
        try {
            const newActivity = new messageActivityModel_1.MessageActivity(req.body);
            await newActivity.save();
            return res.status(201).json({ success: true, data: newActivity });
        }
        catch (error) {
            console.error("Error creating message activity:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * @route GET /api/message-activities
     * @desc 获取所有消息活动
     * @access Private
     */
    async getActivities(req, res) {
        try {
            const activities = await messageActivityModel_1.MessageActivity.find().sort({ createdAt: -1 });
            return res.status(200).json(activities);
        }
        catch (error) {
            console.error("Error fetching message activities:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * @route GET /api/message-activity/:id
     * @desc 根据ID获取单个消息活动
     * @access Private
     */
    async getActivityById(req, res) {
        try {
            const activity = await messageActivityModel_1.MessageActivity.findById(req.params.id);
            if (!activity) {
                return res.status(404).json({ success: false, message: "Message activity not found" });
            }
            return res.status(200).json({ success: true, data: activity });
        }
        catch (error) {
            console.error("Error fetching message activity by ID:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * @route PUT /api/message-activity/:id
     * @desc 更新消息活动
     * @access Private
     */
    async updateActivity(req, res) {
        try {
            const updatedActivity = await messageActivityModel_1.MessageActivity.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
            if (!updatedActivity) {
                return res.status(404).json({ success: false, message: "Message activity not found" });
            }
            return res.status(200).json({ success: true, data: updatedActivity });
        }
        catch (error) {
            console.error("Error updating message activity:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * @route DELETE /api/message-activity/:id
     * @desc 删除消息活动
     * @access Private
     */
    async deleteActivity(req, res) {
        try {
            const deletedActivity = await messageActivityModel_1.MessageActivity.findByIdAndDelete(req.params.id);
            if (!deletedActivity) {
                return res.status(404).json({ success: false, message: "Message activity not found" });
            }
            return res.status(200).json({ success: true, message: "Message activity deleted successfully" });
        }
        catch (error) {
            console.error("Error deleting message activity:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * @route PUT /api/message-activity/:id/status
     * @desc 更新消息活动状态
     * @access Private
     * @param req.body { status: number } 新状态值
     */
    async updateActivityStatus(req, res) {
        try {
            const { id } = req.params;
            const { status } = req.body;
            // 验证状态值是否合法
            if (![0, 1, 2, 3].includes(status)) {
                return res.status(400).json({
                    success: false,
                    message: "Invalid status value. Allowed values: 0 (未发布), 1 (已发布), 2 (已完成), 3 (已中止)",
                });
            }
            // 获取当前活动
            const activity = await messageActivityModel_1.MessageActivity.findById(id);
            if (!activity) {
                return res.status(404).json({ success: false, message: "Message activity not found" });
            }
            // 验证状态变更是否合法
            if (!this.isStatusTransitionValid(activity.status, status)) {
                return res.status(400).json({
                    success: false,
                    message: `Invalid status transition from ${this.getStatusName(activity.status)} to ${this.getStatusName(status)}`,
                });
            }
            // 更新状态
            activity.status = status;
            // 如果是完成或中止状态，记录完成时间
            if (status === 2 || status === 3) {
                activity.completedAt = new Date();
            }
            // 如果是发布状态，记录发布时间
            if (status === 1) {
                activity.publishedAt = new Date();
                // 立即向rabbitmq投递一条消息， 以便异步生成消息推送记录
                await rabbitmqService_1.default.publishActivityMessage(QUEUE_NAME, { activityId: id });
            }
            await activity.save();
            return res.status(200).json({
                success: true,
                data: activity,
                message: `Activity status updated to ${this.getStatusName(status)}`,
            });
        }
        catch (error) {
            console.error("Error updating activity status:", error);
            return res.status(500).json({ success: false, message: "Server error", error: error.message });
        }
    }
    /**
     * 验证状态变更是否合法
     * @param currentStatus 当前状态
     * @param newStatus 新状态
     * @returns 如果变更合法返回true，否则返回false
     */
    isStatusTransitionValid(currentStatus, newStatus) {
        const validTransitions = {
            0: [1], // 未发布 -> 已发布
            1: [2, 3], // 已发布 -> 已完成/已中止
            2: [], // 已完成 -> 不允许变更
            3: [], // 已中止 -> 不允许变更
        };
        return validTransitions[currentStatus]?.includes(newStatus) || false;
    }
    /**
     * 获取状态名称
     */
    getStatusName(status) {
        const statusNames = {
            0: "未发布",
            1: "已发布",
            2: "已完成",
            3: "已中止",
        };
        return statusNames[status] || "未知状态";
    }
}
exports.default = new MessageActivityController();
