package com.jiooption.trading.firebase

import android.util.Log
import com.jiooption.trading.App
import com.jiooption.trading.network.ApiClient
import com.jiooption.trading.network.models.DeviceRegisterRequest
import com.jiooption.trading.utils.Constants
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.*

/**
 * Firebase Cloud Messaging service
 * Handles incoming push notifications and token refresh
 */
class FCMService : FirebaseMessagingService() {

    companion object {
        private const val TAG = "FCMService"
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    /**
     * Called when a new FCM token is generated
     */
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "New FCM token: $token")

        // Save token locally
        App.getSecureStorage().putString(Constants.PREF_FCM_TOKEN, token)

        // Register with server if user is logged in
        if (App.getSecureStorage().isLoggedIn()) {
            registerTokenWithServer(token)
        }
    }

    /**
     * Called when a message is received
     */
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        Log.d(TAG, "Message from: ${remoteMessage.from}")

        // Handle data payload
        val data = remoteMessage.data
        val title = data["title"] ?: remoteMessage.notification?.title ?: "Jiooption"
        val body = data["body"] ?: remoteMessage.notification?.body ?: ""
        val type = data["type"] ?: "system"

        // Determine notification channel based on type
        val channelId = when (type) {
            "trade_result" -> Constants.CHANNEL_TRADES
            "deposit" -> Constants.CHANNEL_DEPOSITS
            "withdrawal" -> Constants.CHANNEL_WITHDRAWALS
            "promo" -> Constants.CHANNEL_PROMO
            else -> Constants.CHANNEL_DEFAULT
        }

        // Show notification
        NotificationHelper.showNotification(
            context = this,
            title = title,
            body = body,
            channelId = channelId,
            data = data
        )
    }

    /**
     * Register FCM token with the backend server
     */
    private fun registerTokenWithServer(token: String) {
        serviceScope.launch {
            try {
                val request = DeviceRegisterRequest(
                    deviceToken = token,
                    deviceType = "android",
                    deviceModel = android.os.Build.MODEL,
                    appVersion = getAppVersion(),
                    osVersion = android.os.Build.VERSION.RELEASE
                )

                val response = ApiClient.getApiService().registerDevice(request)
                if (response.isSuccessful) {
                    Log.d(TAG, "Token registered with server")
                } else {
                    Log.e(TAG, "Token registration failed: ${response.code()}")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Token registration error", e)
            }
        }
    }

    private fun getAppVersion(): String {
        return try {
            packageManager.getPackageInfo(packageName, 0).versionName ?: "1.0.0"
        } catch (e: Exception) {
            "1.0.0"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()
    }
}
