"use strict";
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
         * @returns A JSON response with the newly created record or an error message.
         */
        this.createRecord = async (req, res) => {
            try {
                const newRecord = await this.messageRecordService.createMessageRecord(req.body);
                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.
         * Filters can be applied by uid, activityName, strategyName, templateName, status, and various date fields.
         * Date fields can be filtered by a single date or a range (e.g., "?createdAt=2023-01-01,2023-01-31").
         * @access Private
         * @returns A JSON response with paginated records and the total count.
         */
        this.getPaginatedRecords = async (req, res) => {
            try {
                const { page, limit, sortField, sortOrder, ...filters } = req.query;
                const paginatedRecords = await this.messageRecordService.getPaginatedRecords(parseInt(page) || 1, parseInt(limit) || 10, filters, sortField, sortOrder);
                // return res.status(200).json({
                //         success: true,
                //         data: records,
                //         pagination: {
                //           total,
                //           page: pageNum,
                //           limit: limitNum,
                //           totalPages: Math.ceil(total / limitNum),
                //         },
                //       });
                return res
                    .status(200)
                    .json({
                    success: true,
                    data: paginatedRecords.records,
                    pagination: { total: paginatedRecords.total, page: paginatedRecords.page, limit: paginatedRecords.limit, totalPages: paginatedRecords.totalPages },
                });
            }
            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
         * @returns A JSON response with the records for a specific user.
         */
        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
         * @returns A JSON response with the single record found or a "not found" message.
         */
        this.getRecordById = async (req, res) => {
            try {
                // Validate that the provided ID is a valid MongoDB ObjectId
                if (!(0, mongoose_1.isObjectIdOrHexString)(req.params.id)) {
                    return res.status(400).json({ success: false, message: "Invalid record ID format" });
                }
                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
         * @returns A JSON response with the updated record.
         */
        this.updateRecord = async (req, res) => {
            try {
                if (!(0, mongoose_1.isObjectIdOrHexString)(req.params.id)) {
                    return res.status(400).json({ success: false, message: "Invalid record ID format" });
                }
                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, with optional date and strategy filters.
         * @access Private
         * @returns A JSON response with overall statistics.
         */
        this.getOverallStatistics = async (req, res) => {
            try {
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getOverallStatistics(start, end, stratName);
                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
         * @returns A JSON response with activity-based statistics.
         */
        this.getStatisticsByActivity = async (req, res) => {
            try {
                const { startDate, endDate } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stats = await this.messageRecordService.getStatisticsByActivity(start, end);
                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
         * @returns A JSON response with strategy-based statistics.
         */
        this.getStatisticsByStrategy = async (req, res) => {
            try {
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getStatisticsByStrategy(start, end, stratName);
                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, with optional date and strategy filters.
         * @access Private
         * @returns A JSON response with template-based statistics.
         */
        this.getStatisticsByTemplate = async (req, res) => {
            try {
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getStatisticsByTemplate(start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by template:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/by-cc
         * @desc Retrieves message push statistics grouped by cc, with optional date and strategy filters.
         * @access Private
         * @returns A JSON response with cc-based statistics.
         */
        this.getStatisticsByCc = async (req, res) => {
            try {
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getStatisticsByCc(start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by cc:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/statistics/by-image
         * @desc Retrieves message push statistics grouped by image, with optional date and strategy filters.
         * @access Private
         * @returns A JSON response with image-based statistics.
         */
        this.getStatisticsByImage = async (req, res) => {
            try {
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getStatisticsByImage(start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching statistics by image:", 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, with optional date and strategy filters.
         * @access Private
         * @returns A JSON response with daily trend statistics.
         */
        this.getDailySentTrends = async (req, res) => {
            try {
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                const stats = await this.messageRecordService.getDailySentTrends(start, end, stratName);
                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/multi-dimensional
         * @desc Retrieves multi-dimensional message push statistics
         * @access Private
         * @returns A JSON response with multi-dimensional statistics.
         */
        this.getMultiDimensionalStatistics = async (req, res) => {
            try {
                const { startDate, endDate, templateName, strategyName, cc, image } = req.query;
                const filters = {};
                if (startDate)
                    filters.startDate = new Date(startDate);
                if (endDate)
                    filters.endDate = new Date(endDate);
                if (templateName)
                    filters.templateName = templateName;
                if (strategyName)
                    filters.strategyName = strategyName;
                if (cc)
                    filters.cc = cc;
                if (image)
                    filters.image = image;
                const stats = await this.messageRecordService.getMultiDimensionalStatistics(filters);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching multi-dimensional statistics:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/daily/trends/by-cc/:cc
         * @desc Retrieves daily message trends by country code
         * @access Private
         * @returns A JSON response with daily statistics.
         */
        this.getDailyTrendsByCc = async (req, res) => {
            try {
                const { cc } = req.params;
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                if (!cc) {
                    return res.status(400).json({ success: false, message: "Country code is required." });
                }
                const stats = await this.messageRecordService.getDailyTrendsByCc(cc, start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching daily trends by cc:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/daily/trends/by-strategy/:strategyName
         * @desc Retrieves daily message trends by strategy name
         * @access Private
         * @returns A JSON response with daily statistics.
         */
        this.getDailyTrendsByStrategy = async (req, res) => {
            try {
                const { strategyName } = req.params;
                // 从查询参数中获取 startDate, endDate
                const { startDate, endDate } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                if (!strategyName) {
                    return res.status(400).json({ success: false, message: "Strategy name is required." });
                }
                const stats = await this.messageRecordService.getDailyTrendsByStrategy(strategyName, start, end);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching daily trends by strategy:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/daily/trends/by-template/:templateName
         * @desc Retrieves daily message trends by template ID
         * @access Private
         * @returns A JSON response with daily statistics.
         */
        this.getDailyTrendsByTemplate = async (req, res) => {
            try {
                const { templateName } = req.params;
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                if (!templateName) {
                    return res.status(400).json({ success: false, message: "Template Name is required." });
                }
                const stats = await this.messageRecordService.getDailyTrendsByTemplate(templateName, start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching daily trends by template:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        /**
         * @route GET /api/message/daily/trends/by-image/:image
         * @desc Retrieves daily message trends by image URL
         * @access Private
         * @returns A JSON response with daily statistics.
         */
        this.getDailyTrendsByImage = async (req, res) => {
            try {
                const { image } = req.params;
                // 从查询参数中获取 startDate, endDate 和 strategyName
                const { startDate, endDate, strategyName } = req.query;
                const start = startDate ? new Date(startDate) : undefined;
                const end = endDate ? new Date(endDate) : undefined;
                const stratName = strategyName ? strategyName : undefined;
                if (!image) {
                    return res.status(400).json({ success: false, message: "Image URL is required." });
                }
                const stats = await this.messageRecordService.getDailyTrendsByImage(image, start, end, stratName);
                return res.status(200).json({ success: true, data: stats });
            }
            catch (error) {
                console.error("Error fetching daily trends by image:", error);
                return res.status(500).json({ success: false, message: "Server error", error: error.message });
            }
        };
        this.messageRecordService = new messageRecordService_1.MessageRecordService();
    }
}
exports.default = new MessageRecordController();
