package pl.firmatpp.kierowca.sync

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import pl.firmatpp.kierowca.data.DriverRepository
import pl.firmatpp.kierowca.data.sync.NetworkMonitor

class DriverFirebaseMessagingService : FirebaseMessagingService() {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    override fun onNewToken(token: String) {
        scope.launch {
            val repository = DriverRepository(applicationContext)
            if (repository.hasToken() && NetworkMonitor(applicationContext).isCurrentlyValidated()) {
                runCatching { repository.storePushToken(token) }
            }
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        val data = message.data
        if (data["type"] == "driver_new_route_notification") {
            NewRouteNotificationWorker.enqueue(
                context = applicationContext,
                routeId = data["routeId"],
                date = data["date"],
            )
            return
        }

        if (data["type"] == "driver_leave_request_decision") {
            LeaveRequestDecisionNotificationWorker.enqueue(
                context = applicationContext,
                leaveRequestId = data["leaveRequestId"],
                title = data["title"],
                body = data["body"],
            )
            if (!DriverRuntimeSyncState.websocketOwnsForegroundHints()) {
                DriverSyncWorker.enqueue(
                    context = applicationContext,
                    date = data["date"],
                    routeId = data["routeId"],
                )
            }
            return
        }

        if (data["type"] != "driver_sync_hint") return
        if (DriverRuntimeSyncState.websocketOwnsForegroundHints()) return

        DriverSyncWorker.enqueue(
            context = applicationContext,
            date = data["date"],
            routeId = data["routeId"],
            scope = data["scope"],
            version = data["version"]?.toLongOrNull(),
            checksum = data["checksum"],
        )
    }
}
