package com.devlab.app.service

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.AppNotification
import com.devlab.app.data.model.FcmRegisterRequest
import com.devlab.app.util.NotificationHelper
import com.devlab.app.util.PreferencesManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class ServerManagerFirebaseService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "New FCM token: $token")

        CoroutineScope(Dispatchers.IO).launch {
            val prefs = PreferencesManager(this@ServerManagerFirebaseService)
            prefs.saveFcmToken(token)

            val apiToken = prefs.getToken()
            if (apiToken.isNotBlank()) {
                registerTokenWithBackend(token, apiToken)
            }
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        Log.d(TAG, "FCM message received: ${message.data}")

        val title = message.notification?.title
            ?: message.data["title"]
            ?: "Notification"

        val body = message.notification?.body
            ?: message.data["message"]
            ?: ""

        val type = message.data["type"] ?: "info"
        val noteId = (message.data["notification_id"] ?: "0").toIntOrNull() ?: 0

        showNotification(title, body, type, noteId)
    }

    private fun showNotification(title: String, body: String, type: String, noteId: Int) {
        val notification = AppNotification(
            id = noteId,
            title = title,
            message = body,
            type = type,
            is_read = 0,
            created_at = "",
        )
        NotificationHelper.showNotification(this, notification)
    }

    private suspend fun registerTokenWithBackend(token: String, apiToken: String) {
        try {
            RetrofitClient.setToken(apiToken)
            val service = RetrofitClient.getApiService()
            service.registerFcmToken(FcmRegisterRequest(token))
            Log.d(TAG, "FCM token registered with backend")
        } catch (e: Exception) {
            Log.e(TAG, "Failed to register FCM token: ${e.message}")
        }
    }

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