package com.simplecleaner.app.business.push.fcm

import android.content.Context
import android.util.Log
import com.simplecleaner.app.SpConstObject.fcmToken
import com.simplecleaner.app.business.helper.EventUtils.event
import com.simplecleaner.app.utils.LogEx
import com.google.android.gms.tasks.Task
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import org.json.JSONObject

object FCMManager {
    /**
     * 初始化Firebase并获取Token
     */
    fun initFirebase(context: Context?) {
        FirebaseApp.initializeApp(context!!)
        LogEx.logDebug("FCM", "FirebaseApp initialized")
        fetchAndReportToken()
    }

    /**
     * 订阅Topic并处理回调
     */
    fun subscribeToTopic(topic: String) {
        LogEx.logDebug("FCM", "subscribeToTopic: $topic")
        FirebaseMessaging.getInstance().subscribeToTopic(topic)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    fetchAndReportToken()
                    LogEx.logDebug("FCM", "subscribeToTopic success: $topic")
                    event("FCM_Topic_$topic", null, null)
                } else {
                    LogEx.logDebug("FCM", "subscribeToTopic failed: $topic, exception=${task.exception}")
                    event("FCM_Error", "subscribeToTopic task.isSuccessful=${task.isSuccessful} ", null)
                }
            }
    }

    /**
     * 退订Topic并处理回调（仅日志，无event）
     */
    fun unsubscribeFromTopic(topic: String?) {
        if (topic.isNullOrEmpty()) return
        LogEx.logDebug("FCM", "unsubscribeFromTopic: $topic")
        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    LogEx.logDebug("FCM", "unsubscribeFromTopic success: $topic")
                } else {
                    LogEx.logDebug("FCM", "unsubscribeFromTopic failed: $topic, exception=${task.exception}")
                }
            }
    }

    /**
     * 获取并上报FCM Token（只在成功时上报event）
     */
    private fun fetchAndReportToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener { task ->
                if (!task.isSuccessful) {
                    LogEx.logDebug("FCM", "Fetching FCM registration token failed: ${task.exception}")
                    return@addOnCompleteListener
                }
                val token = task.result
                fcmToken = token
                val json = JSONObject().apply { put("token", token) }
                event("fcm_message_received", ext = json)
                LogEx.logDebug("FCM", "FCM Registration Token: $token")
            }
    }
}


