"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageRecordService = void 0;
const messageRecordModel_1 = require("../models/messageRecordModel");
class MessageRecordService {
    /**
     * 创建一条新的消息推送记录
     * @param recordData 消息记录数据
     * @returns 新创建的消息记录对象
     */
    async createMessageRecord(recordData) {
        const newRecord = new messageRecordModel_1.MessageRecord(recordData);
        return await newRecord.save();
    }
    /**
     * 分页获取消息推送记录，支持筛选和排序
     * @param page 页码
     * @param limit 每页记录数
     * @param filters 筛选条件
     * @param sortField 排序字段
     * @param sortOrder 排序顺序 ('asc' 或 'desc')
     * @returns 包含记录和总数的对象
     */
    async getPaginatedRecords(page = 1, limit = 10, filters = {}, sortField = "createdAt", sortOrder = "desc") {
        // 构建查询条件
        const query = {};
        if (filters.uid) {
            query.uid = filters.uid;
        }
        if (filters.activityName) {
            query.activityName = filters.activityName;
        }
        if (filters.templateName) {
            query.templateName = filters.templateName;
        }
        if (filters.status !== undefined) {
            query.status = filters.status;
        }
        if (filters.createdAt) {
            const dates = filters.createdAt.split(",");
            const startDate = new Date(dates[0]);
            if (dates.length > 1) {
                const endDate = new Date(dates[1]);
                query.createdAt = { $gte: startDate, $lte: endDate };
            }
            else {
                query.createdAt = { $gte: startDate };
            }
        }
        if (filters.sentAt) {
            const dates = filters.sentAt.split(",");
            const startDate = new Date(dates[0]);
            if (dates.length > 1) {
                const endDate = new Date(dates[1]);
                query.sentAt = { $gte: startDate, $lte: endDate };
            }
            else {
                query.sentAt = { $gte: startDate };
            }
        }
        if (filters.displayedAt) {
            const dates = filters.displayedAt.split(",");
            const startDate = new Date(dates[0]);
            if (dates.length > 1) {
                const endDate = new Date(dates[1]);
                query.displayedAt = { $gte: startDate, $lte: endDate };
            }
            else {
                query.displayedAt = { $gte: startDate };
            }
        }
        if (filters.openedAt) {
            const dates = filters.openedAt.split(",");
            const startDate = new Date(dates[0]);
            if (dates.length > 1) {
                const endDate = new Date(dates[1]);
                query.openedAt = { $gte: startDate, $lte: endDate };
            }
            else {
                query.openedAt = { $gte: startDate };
            }
        }
        const sortOption = {};
        sortOption[sortField] = sortOrder === "asc" ? 1 : -1;
        const total = await messageRecordModel_1.MessageRecord.countDocuments(query);
        const records = await messageRecordModel_1.MessageRecord.find(query)
            .sort(sortOption)
            .skip((page - 1) * limit)
            .limit(limit);
        const totalPages = Math.ceil(total / limit);
        return { records, total, page, limit, totalPages };
    }
    /**
     * 根据用户UID获取其所有消息推送记录
     * @param uid 用户UID
     * @returns 消息记录列表
     */
    async getRecordsByUid(uid) {
        return await messageRecordModel_1.MessageRecord.find({ uid }).sort({ createdAt: -1 });
    }
    /**
     * 根据消息活动ID获取所有相关的推送记录
     * @param activityId 消息活动ID
     * @returns 消息记录列表
     */
    async getRecordsByActivityId(activityId) {
        return await messageRecordModel_1.MessageRecord.find({ activityId }).sort({ createdAt: -1 });
    }
    /**
     * 根据ID获取单个消息推送记录
     * @param recordId 消息记录ID
     * @returns 消息记录对象或null
     */
    async getSingleRecord(recordId) {
        return await messageRecordModel_1.MessageRecord.findById(recordId);
    }
    /**
     * 更新消息推送记录的状态，常用于更新推送状态
     * @param recordId 消息记录ID
     * @param updateData 更新数据
     * @returns 更新后的消息记录对象
     */
    async updateMessageRecord(recordId, updateData) {
        return await messageRecordModel_1.MessageRecord.findByIdAndUpdate(recordId, updateData, { new: true });
    }
    /**
     * 获取整体消息推送统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     */
    async getOverallStatistics(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果存在任何筛选条件，则添加 $match 阶段
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 按状态和inforeground字段分组，计算每个类别的记录数
            {
                $group: {
                    _id: { status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，计算总数、发送成功数、送达数、打开数、展示数
            {
                $group: {
                    _id: null,
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            });
            const result = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return result[0];
        }
        catch (error) {
            console.error("Error fetching overall statistics:", error);
            return null;
        }
    }
    /**
     * 按活动获取消息统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     */
    async getStatisticsByActivity(startDate, endDate) {
        try {
            const pipeline = [];
            // 如果提供了日期，添加 $match 阶段
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                pipeline.push({
                    $match: {
                        createdAt: {
                            $gte: startDate,
                            $lte: endDate,
                        },
                    },
                });
            }
            else if (startDate) {
                pipeline.push({
                    $match: {
                        createdAt: {
                            $gte: startDate,
                        },
                    },
                });
            }
            else if (endDate) {
                pipeline.push({
                    $match: {
                        createdAt: {
                            $lte: endDate,
                        },
                    },
                });
            }
            pipeline.push(
            // 1. 根据 activityId, status, 和 inforeground 进行分组
            {
                $group: {
                    _id: {
                        activityId: "$activityId",
                        activityName: "$activityName",
                        status: "$status",
                        inforeground: "$inforeground",
                    },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，以便按 activityId 汇总
            {
                $group: {
                    _id: "$_id.activityId",
                    activityName: { $first: "$_id.activityName" },
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    activityId: "$_id",
                    activityName: "$activityName",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 4. 按 deliveredRate 降序排序
            {
                $sort: { deliveredRate: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching statistics by activity:", error);
            return [];
        }
    }
    /**
     * 按策略获取消息统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称
     */
    async getStatisticsByStrategy(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 如果提供了日期，添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = {
                    $gte: startDate,
                };
            }
            else if (endDate) {
                matchConditions.createdAt = {
                    $lte: endDate,
                };
            }
            // 如果提供了 strategyName，添加策略名称筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果有任何筛选条件，将 $match 阶段添加到管道
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 根据 strategyId, status, 和 inforeground 进行分组
            {
                $group: {
                    _id: {
                        strategyId: "$strategyId",
                        strategyName: "$strategyName",
                        status: "$status",
                        inforeground: "$inforeground",
                    },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，以便按 strategyId 汇总
            {
                $group: {
                    _id: "$_id.strategyId",
                    strategyName: { $first: "$_id.strategyName" },
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    strategyId: "$_id",
                    strategyName: "$strategyName",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 4. 按 deliveredRate 降序排序
            {
                $sort: { deliveredRate: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching statistics by strategy:", error);
            return [];
        }
    }
    /**
     * 按模板获取消息统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称
     */
    async getStatisticsByTemplate(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 如果提供了日期，添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = {
                    $gte: startDate,
                };
            }
            else if (endDate) {
                matchConditions.createdAt = {
                    $lte: endDate,
                };
            }
            // 如果提供了 strategyName，添加策略名称筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果有任何筛选条件，将 $match 阶段添加到管道
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 根据 templateId, status, 和 inforeground 进行分组
            {
                $group: {
                    _id: {
                        templateId: "$templateId",
                        templateName: "$templateName",
                        status: "$status",
                        inforeground: "$inforeground",
                    },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，以便按 templateId 汇总
            {
                $group: {
                    _id: "$_id.templateId",
                    templateName: { $first: "$_id.templateName" },
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    templateId: "$_id",
                    templateName: "$templateName",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 4. 按 deliveredRate 降序排序
            {
                $sort: { deliveredRate: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching statistics by template:", error);
            return [];
        }
    }
    /**
     * 按时间维度的趋势分析，每日统计
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     */
    async getDailySentTrends(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果存在任何筛选条件，则添加 $match 阶段
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 将 createdAt 字段转换为日期，忽略时分秒
            {
                $project: {
                    _id: 0,
                    date: {
                        $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" },
                    },
                    status: "$status",
                    inforeground: "$inforeground",
                },
            }, 
            // 2. 根据日期、状态和 inforeground 进行分组
            {
                $group: {
                    _id: { date: "$date", status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, 
            // 3. 将数据重组，以便按日期汇总
            {
                $group: {
                    _id: "$_id.date",
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 4. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    date: "$_id",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 5. 按日期升序排序
            {
                $sort: { date: 1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching daily sent trends:", error);
            return [];
        }
    }
    /**
     * 按国家代码获取消息统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     */
    async getStatisticsByCc(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果存在任何筛选条件，则添加 $match 阶段
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 根据 cc, status, strategyName 和 inforeground 进行分组
            {
                $group: {
                    _id: {
                        cc: "$cc",
                        status: "$status",
                        inforeground: "$inforeground",
                        strategyName: "$strategyName", // 增加 strategyName
                    },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，以便按 cc 汇总
            {
                $group: {
                    _id: "$_id.cc",
                    cc: { $first: "$_id.cc" },
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    cc: "$cc",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 4. 按 deliveredRate 降序排序
            {
                $sort: { deliveredRate: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching statistics by cc:", error);
            return [];
        }
    }
    /**
     * 按图片 URL 获取消息统计数据
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     */
    async getStatisticsByImage(startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {};
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 如果存在任何筛选条件，则添加 $match 阶段
            if (Object.keys(matchConditions).length > 0) {
                pipeline.push({
                    $match: matchConditions,
                });
            }
            pipeline.push(
            // 1. 根据 image, status, strategyName 和 inforeground 进行分组
            {
                $group: {
                    _id: {
                        image: "$image",
                        status: "$status",
                        inforeground: "$inforeground",
                        strategyName: "$strategyName", // 增加 strategyName
                    },
                    count: { $sum: 1 },
                },
            }, 
            // 2. 将数据重组，以便按 image 汇总
            {
                $group: {
                    _id: "$_id.image",
                    image: { $first: "$_id.image" },
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 3. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    image: "$image",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 4. 按 deliveredRate 降序排序
            {
                $sort: { deliveredRate: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching statistics by image:", error);
            return [];
        }
    }
    /**
     * 按多个维度获取消息推送统计数据。
     * 支持日期范围、模板、图片、国家和策略的组合查询。
     * @param filters 包含查询条件的过滤器对象
     * @returns 多维度统计结果
     */
    async getMultiDimensionalStatistics(filters) {
        try {
            const pipeline = [];
            // 1. $match (筛选阶段)
            const matchStage = {};
            if (filters.startDate || filters.endDate) {
                matchStage.createdAt = {};
                if (filters.startDate) {
                    matchStage.createdAt.$gte = filters.startDate;
                }
                if (filters.endDate) {
                    // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                    if (filters.startDate && filters.endDate.getTime() <= filters.startDate.getTime()) {
                        filters.endDate = new Date(filters.startDate.getTime() + 24 * 60 * 60 * 1000);
                    }
                    matchStage.createdAt.$lte = filters.endDate;
                }
            }
            if (filters.templateName) {
                matchStage.templateName = filters.templateName;
            }
            if (filters.strategyName) {
                matchStage.strategyName = filters.strategyName;
            }
            if (filters.cc) {
                matchStage.cc = filters.cc;
            }
            if (filters.image) {
                matchStage.image = filters.image;
            }
            if (Object.keys(matchStage).length > 0) {
                pipeline.push({ $match: matchStage });
            }
            // 2. $group (分组和聚合阶段)
            pipeline.push({
                $group: {
                    _id: {
                        date: { $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" } },
                        templateName: "$templateName",
                        strategyName: "$strategyName",
                        cc: "$cc",
                        image: "$image",
                        status: "$status",
                        inforeground: "$inforeground",
                    },
                    count: { $sum: 1 },
                },
            });
            // 3. 第二次 $group (汇总阶段)
            pipeline.push({
                $group: {
                    _id: {
                        date: "$_id.date",
                        templateName: "$_id.templateName",
                        strategyName: "$_id.strategyName",
                        cc: "$_id.cc",
                        image: "$_id.image",
                    },
                    totalRecords: { $sum: "$count" },
                    sent: { $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] } },
                    delivered: { $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] } },
                    opened: { $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] } },
                    failed: { $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] } },
                    displayCount: {
                        $sum: {
                            $cond: [{ $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }] }, "$count", 0],
                        },
                    },
                },
            });
            // 4. $project (计算比率和格式化输出)
            pipeline.push({
                $project: {
                    _id: 0,
                    date: "$_id.date",
                    templateName: "$_id.templateName",
                    strategyName: "$_id.strategyName",
                    cc: "$_id.cc",
                    image: "$_id.image",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            });
            // 5. $sort (排序)
            pipeline.push({
                $sort: { date: 1, templateName: 1, cc: 1, image: 1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching multi-dimensional statistics:", error);
            return [];
        }
    }
    /**
     * 按国家代码和时间维度获取每日统计数据
     * @param cc 必须提供的国家代码
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     * @returns 每日统计数据列表
     */
    async getDailyTrendsByCc(cc, startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {
                cc: cc,
            };
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 添加 $match 阶段
            pipeline.push({
                $match: matchConditions,
            });
            pipeline.push(
            // 1. 将 createdAt 字段转换为日期，忽略时分秒
            {
                $project: {
                    _id: 0,
                    date: {
                        $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" },
                    },
                    status: "$status",
                    inforeground: "$inforeground",
                },
            }, 
            // 2. 根据日期、状态和 inforeground 进行分组
            {
                $group: {
                    _id: { date: "$date", status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, 
            // 3. 将数据重组，以便按日期汇总
            {
                $group: {
                    _id: "$_id.date",
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 4. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    date: "$_id",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 5. 按日期降序排序
            {
                $sort: { date: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching daily trends by cc:", error);
            return [];
        }
    }
    /**
     * 按策略名称和时间维度获取每日统计数据
     * @param strategyName 必须提供的策略名称
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @returns 每日统计数据列表
     */
    async getDailyTrendsByStrategy(strategyName, startDate, endDate) {
        try {
            const pipeline = [];
            const matchConditions = {
                strategyName: strategyName,
            };
            // 添加日期筛选条件
            if (startDate && endDate) {
                // 容错处理：如果 endDate <= startDate，将 endDate 设为 startDate 的后一天
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 $match 阶段
            pipeline.push({
                $match: matchConditions,
            });
            pipeline.push(
            // 1. 将 createdAt 字段转换为日期，忽略时分秒
            {
                $project: {
                    _id: 0,
                    date: {
                        $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" },
                    },
                    status: "$status",
                    inforeground: "$inforeground",
                },
            }, 
            // 2. 根据日期、状态和 inforeground 进行分组
            {
                $group: {
                    _id: { date: "$date", status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, 
            // 3. 将数据重组，以便按日期汇总
            {
                $group: {
                    _id: "$_id.date",
                    totalRecords: { $sum: "$count" },
                    sent: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] },
                    },
                    delivered: {
                        $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] },
                    },
                    opened: {
                        $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] },
                    },
                    failed: {
                        $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] },
                    },
                    displayCount: {
                        $sum: {
                            $cond: [
                                {
                                    $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }],
                                },
                                "$count",
                                0,
                            ],
                        },
                    },
                },
            }, 
            // 4. 计算比率并格式化输出
            {
                $project: {
                    _id: 0,
                    date: "$_id",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }],
                    },
                    deliveredRate: {
                        $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }],
                    },
                    displayRate: {
                        $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }],
                    },
                    clickThroughRate: {
                        $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }],
                    },
                    tokenInvalidationRate: {
                        $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }],
                    },
                },
            }, 
            // 5. 按日期升序排序（统一为升序，与getDailyTrendsByCc保持一致）
            {
                $sort: { date: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching daily trends by strategy:", error);
            return [];
        }
    }
    /**
     * 按模板ID和时间维度获取每日统计数据
     * @param templateName 必须提供的模板ID
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     * @returns 每日统计数据列表
     */
    async getDailyTrendsByTemplate(templateName, startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {
                templateName: templateName,
            };
            if (startDate && endDate) {
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 添加 $match 阶段
            pipeline.push({
                $match: matchConditions,
            });
            pipeline.push({
                $project: {
                    _id: 0,
                    date: { $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" } },
                    status: "$status",
                    inforeground: "$inforeground",
                },
            }, {
                $group: {
                    _id: { date: "$date", status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, {
                $group: {
                    _id: "$_id.date",
                    totalRecords: { $sum: "$count" },
                    sent: { $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] } },
                    delivered: { $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] } },
                    opened: { $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] } },
                    failed: { $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] } },
                    displayCount: {
                        $sum: { $cond: [{ $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }] }, "$count", 0] },
                    },
                },
            }, {
                $project: {
                    _id: 0,
                    date: "$_id",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: { $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }] },
                    deliveredRate: { $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }] },
                    displayRate: { $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }] },
                    clickThroughRate: { $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }] },
                    tokenInvalidationRate: { $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }] },
                },
            }, {
                $sort: { date: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching daily trends by template:", error);
            return [];
        }
    }
    /**
     * 按图片URL和时间维度获取每日统计数据
     * @param image 必须提供的图片URL
     * @param startDate 可选的开始日期
     * @param endDate 可选的结束日期
     * @param strategyName 可选的策略名称筛选
     * @returns 每日统计数据列表
     */
    async getDailyTrendsByImage(image, startDate, endDate, strategyName) {
        try {
            const pipeline = [];
            const matchConditions = {
                image: image,
            };
            if (startDate && endDate) {
                if (endDate.getTime() <= startDate.getTime()) {
                    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
                }
                matchConditions.createdAt = {
                    $gte: startDate,
                    $lte: endDate,
                };
            }
            else if (startDate) {
                matchConditions.createdAt = { $gte: startDate };
            }
            else if (endDate) {
                matchConditions.createdAt = { $lte: endDate };
            }
            // 添加 strategyName 筛选条件
            if (strategyName) {
                matchConditions.strategyName = strategyName;
            }
            // 添加 $match 阶段
            pipeline.push({
                $match: matchConditions,
            });
            pipeline.push({
                $project: {
                    _id: 0,
                    date: { $dateTrunc: { date: "$createdAt", unit: "day", timezone: "America/Los_Angeles" } },
                    status: "$status",
                    inforeground: "$inforeground",
                },
            }, {
                $group: {
                    _id: { date: "$date", status: "$status", inforeground: "$inforeground" },
                    count: { $sum: 1 },
                },
            }, {
                $group: {
                    _id: "$_id.date",
                    totalRecords: { $sum: "$count" },
                    sent: { $sum: { $cond: [{ $gte: ["$_id.status", 1] }, "$count", 0] } },
                    delivered: { $sum: { $cond: [{ $gte: ["$_id.status", 2] }, "$count", 0] } },
                    opened: { $sum: { $cond: [{ $eq: ["$_id.status", 3] }, "$count", 0] } },
                    failed: { $sum: { $cond: [{ $eq: ["$_id.status", -1] }, "$count", 0] } },
                    displayCount: {
                        $sum: { $cond: [{ $and: [{ $gte: ["$_id.status", 2] }, { $eq: ["$_id.inforeground", false] }] }, "$count", 0] },
                    },
                },
            }, {
                $project: {
                    _id: 0,
                    date: "$_id",
                    totalRecords: "$totalRecords",
                    sent: "$sent",
                    delivered: "$delivered",
                    opened: "$opened",
                    failed: "$failed",
                    displayCount: "$displayCount",
                    sentSuccessRate: { $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$sent", "$totalRecords"] }] },
                    deliveredRate: { $cond: [{ $eq: ["$sent", 0] }, 0, { $divide: ["$delivered", "$sent"] }] },
                    displayRate: { $cond: [{ $eq: ["$delivered", 0] }, 0, { $divide: ["$displayCount", "$delivered"] }] },
                    clickThroughRate: { $cond: [{ $eq: ["$displayCount", 0] }, 0, { $divide: ["$opened", "$displayCount"] }] },
                    tokenInvalidationRate: { $cond: [{ $eq: ["$totalRecords", 0] }, 0, { $divide: ["$failed", "$totalRecords"] }] },
                },
            }, {
                $sort: { date: -1 },
            });
            const results = await messageRecordModel_1.MessageRecord.aggregate(pipeline);
            return results;
        }
        catch (error) {
            console.error("Error fetching daily trends by image:", error);
            return [];
        }
    }
}
exports.MessageRecordService = MessageRecordService;
