package com.seven.ikar.kotlin.core.push

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

data class PendingPushNavigation(
    val chatId: String,
    val messageId: String?,
    val requestId: Long = System.nanoTime()
)

class IncomingPushNavigationStore {
    private val _pendingNavigation = MutableStateFlow<PendingPushNavigation?>(null)
    val pendingNavigation: StateFlow<PendingPushNavigation?> = _pendingNavigation.asStateFlow()

    fun setPendingChat(chatId: String?, messageId: String?) {
        val normalizedChatId = chatId?.takeIf { it.isNotBlank() } ?: run {
            _pendingNavigation.value = null
            return
        }
        _pendingNavigation.value = PendingPushNavigation(
            chatId = normalizedChatId,
            messageId = messageId?.takeIf { it.isNotBlank() }
        )
    }

    fun setPendingChatId(chatId: String?) {
        setPendingChat(chatId = chatId, messageId = null)
    }

    fun clear(requestId: Long? = null) {
        val current = _pendingNavigation.value ?: return
        if (requestId == null || current.requestId == requestId) {
            _pendingNavigation.value = null
        }
    }
}
