"use strict";
// oms/src/controllers/messageRecordController.ts
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose_1 = require("mongoose");
const messageRecordModel_1 = require("../models/messageRecordModel");
const messageRecordService_1 = require("../services/messageRecordService");
class MessageRecordController {
    constructor() {
        /**
         * @route POST /api/message-record
         * @desc Creates a new message record
         * @access Private
         */
        this.createRecord = async (req, res) => {
            try {
                const newRecord = new messageRecordModel_1.MessageRecord(req.body);
                await newRecord.save();
                return res.status(201).json({ success: true, data: newRecord });
            }
            catch (error) {
                console.error("Error creating message record:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message-records
         * @desc Retrieves all message records with pagination and optional filters
         * @access Private
         */
        this.getPaginatedRecords = async (req, res) => {
            const { page = 1, limit = 30, uid, activityName, templateName, strategyName, status, startDate, endDate } = req.query;
            const pageNum = parseInt(page, 10);
            const limitNum = parseInt(limit, 10);
            // 动态构建查询过滤器
            const filters = {};
            if (uid) {
                filters.uid = uid;
            }
            if (status) {
                const statusNum = parseInt(status, 10);
                if (!isNaN(statusNum)) {
                    filters.status = statusNum;
                }
            }
            if (activityName) {
                filters.activityName = activityName;
            }
            if (strategyName) {
                filters.strategyName = strategyName;
            }
            if (templateName) {
                filters.templateName = templateName;
            }
            // 定义所有可查询的日期字段
            const dateQueryKeys = ["plannedSendAt", "actualSendAt", "deliveredAt", "openedAt", "createdAt", "updatedAt"];
            // 遍历所有日期字段，处理单个日期或日期范围
            dateQueryKeys.forEach((key) => {
                const queryValue = req.query[key];
                if (queryValue) {
                    const dates = queryValue.split(",");
                    if (dates.length === 2) {
                        const startDate = new Date(dates[0]);
                        const endDate = new Date(dates[1]);
                        // 确保日期有效
                        if (!isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
                            filters[key] = {
                                $gte: startDate,
                                $lte: endDate,
                            };
                        }
                        else {
                            console.warn(`[API] Invalid date range format for ${key}: ${queryValue}. Skipping.`);
                        }
                    }
                    else {
                        // 如果不是范围，则按单个日期精确匹配
                        const singleDate = new Date(queryValue);
                        if (!isNaN(singleDate.getTime())) {
                            filters[key] = singleDate;
                        }
                    }
                }
            });
            // 保留对原有startDate/endDate参数的兼容性，并将其应用于createdAt
            if (startDate || endDate) {
                // 确保 createdAt 过滤器不存在冲突，如果已通过范围查询设置，则跳过
                if (!filters.createdAt) {
                    filters.createdAt = {};
                }
                if (startDate) {
                    filters.createdAt.$gte = new Date(startDate);
                }
                if (endDate) {
                    filters.createdAt.$lte = new Date(endDate);
                }
            }
            try {
                const records = await messageRecordModel_1.MessageRecord.find(filters)
                    .sort({ createdAt: -1 })
                    .skip((pageNum - 1) * limitNum)
                    .limit(limitNum);
                const total = await messageRecordModel_1.MessageRecord.countDocuments(filters);
                return res.status(200).json({
                    success: true,
                    data: records,
                    pagination: {
                        total,
                        page: pageNum,
                        limit: limitNum,
                        totalPages: Math.ceil(total / limitNum),
                    },
                });
            }
            catch (error) {
                console.error("Error fetching paginated records:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message-records/user/:uid
         * @desc Retrieves message records by user UID
         * @access Private
         */
        this.getRecordsByUid = async (req, res) => {
            try {
                const records = await messageRecordModel_1.MessageRecord.find({ uid: req.params.uid }).sort({ createdAt: -1 });
                if (!records || records.length === 0) {
                    return res.status(404).json({ success: false, message: "No records found for this user" });
                }
                return res.status(200).json({ success: true, data: records });
            }
            catch (error) {
                console.error("Error fetching records by user UID:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message-record/:id
         * @desc Retrieves a single message record by ID
         * @access Private
         */
        this.getRecordById = async (req, res) => {
            try {
                // 检查 id 是否是有效的 ObjectId 格式
                if (!(0, mongoose_1.isObjectIdOrHexString)(req.params.id)) {
                    return res.status(400).json({ success: false, message: "Invalid record ID" });
                }
                const record = await messageRecordModel_1.MessageRecord.findById(req.params.id);
                if (!record) {
                    return res.status(404).json({ success: false, message: "Message record not found" });
                }
                return res.status(200).json({ success: true, data: record });
            }
            catch (error) {
                console.error("Error fetching message record by ID:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route PUT /api/message-record/:id
         * @desc Updates the status of a message record
         * @access Private
         */
        this.updateRecord = async (req, res) => {
            try {
                // 检查 id 是否是有效的 ObjectId 格式
                if (!(0, mongoose_1.isObjectIdOrHexString)(req.params.id)) {
                    return res.status(400).json({ success: false, message: "Invalid record ID" });
                }
                const updatedRecord = await messageRecordModel_1.MessageRecord.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
                if (!updatedRecord) {
                    return res.status(404).json({ success: false, message: "Message record not found" });
                }
                return res.status(200).json({ success: true, data: updatedRecord });
            }
            catch (error) {
                console.error("Error updating message record:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/overall
         * @desc Retrieves overall message push statistics
         * @access Private
         */
        this.getOverallStatistics = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getOverallStatistics();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching overall statistics:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/by-activity
         * @desc Retrieves message push statistics grouped by activity
         * @access Private
         */
        this.getStatisticsByActivity = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getStatisticsByActivity();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by activity:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/by-strategy
         * @desc Retrieves message push statistics grouped by strategy
         * @access Private
         */
        this.getStatisticsByStrategy = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getStatisticsByStrategy();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by strategy:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/by-template
         * @desc Retrieves message push statistics grouped by template
         * @access Private
         */
        this.getStatisticsByTemplate = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getStatisticsByTemplate();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by strategy:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/daily-trends
         * @desc Retrieves daily sent trend statistics
         * @access Private
         */
        this.getDailySentTrends = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getDailySentTrends();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching daily sent trends:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/avg-delivery-time
         * @desc Retrieves average message delivery time
         * @access Private
         */
        this.getAverageDeliveryTime = async (req, res) => {
            try {
                const stats = await this.messageRecordService.getAverageDeliveryTime();
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching average delivery time:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        this.messageRecordService = new messageRecordService_1.MessageRecordService();
    }
}
exports.default = new MessageRecordController();
