"use strict";
// oms/src/services/fcmService.ts
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FCMService = void 0;
const admin = __importStar(require("firebase-admin"));
const path_1 = __importDefault(require("path"));
// 从配置文件加载服务账号
// 服务账号文件路径在 oms/config/fcm-service-account.json
const serviceAccount = require(path_1.default.join(__dirname, "../../config/fcm-service-account.json"));
/**
 * FCMService 类，用于处理 Firebase Cloud Messaging 的消息发送逻辑。
 * 使用单例模式确保 Firebase app 只初始化一次。
 */
class FCMService {
    constructor() {
        // 检查 Firebase 是否已初始化，避免重复初始化
        if (!admin.apps.length) {
            admin.initializeApp({
                credential: admin.credential.cert(serviceAccount),
            });
            console.log("Firebase Admin SDK initialized successfully.");
        }
    }
    /**
     * 获取 FCMService 的单例实例。
     * @returns FCMService 实例
     */
    static getInstance() {
        if (!FCMService.instance) {
            FCMService.instance = new FCMService();
        }
        return FCMService.instance;
    }
    /**
     * 发送 FCM 消息。
     * @param deviceToken 接收消息的设备令牌
     * @param data 消息数据，用于客户端解析
     * @returns 成功则返回消息 ID，失败则返回错误信息
     */
    async sendMessage(deviceToken, data) {
        const message = {
            data: data,
            token: deviceToken,
        };
        try {
            const response = await admin.messaging().send(message);
            console.log("Successfully sent message:", response);
            return response; // response is the message ID
        }
        catch (error) {
            console.error("Error sending message:", error);
            return error;
        }
    }
    /**
     * 批量发送 FCM 消息给多个设备令牌。
     * @param tokens 接收消息的设备令牌数组
     * @param data 消息数据，用于客户端解析
     * @returns 批量发送结果，包含每个令牌的成功/失败信息
     */
    async sendBatch(tokens, data) {
        const message = {
            data: data,
            tokens: tokens,
        };
        try {
            const response = await admin.messaging().sendEachForMulticast(message);
            console.log(`Successfully sent batch message: ${response.successCount} succeeded, ${response.failureCount} failed.`);
            return response;
        }
        catch (error) {
            console.error("Error sending message batch:", error);
            // 构建一个符合 FirebaseError 类型的对象来满足类型要求
            const firebaseError = {
                code: "messaging/unknown-error",
                message: `Failed to send batch: ${error.message}`,
                toJSON: () => ({ code: "messaging/unknown-error", message: `Failed to send batch: ${error.message}` }),
            };
            return {
                successCount: 0,
                failureCount: tokens.length,
                responses: tokens.map(() => ({
                    success: false,
                    error: firebaseError,
                })),
            };
        }
    }
}
exports.FCMService = FCMService;
