package com.seven.ikar.kotlin.core.navigation

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

data class PendingLinkNavigation(
    val inviteToken: String? = null,
    val publicChannelUsername: String? = null,
    val requestId: Long = System.nanoTime()
)

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

    fun setPendingInvite(inviteToken: String?) {
        val normalizedToken = inviteToken?.trim()?.takeIf { it.isNotBlank() } ?: run {
            _pendingNavigation.value = null
            return
        }
        _pendingNavigation.value = PendingLinkNavigation(inviteToken = normalizedToken)
    }

    fun setPendingPublicChannel(username: String?) {
        val normalizedUsername = username
            ?.trim()
            ?.trimStart('@')
            ?.takeIf { it.isNotBlank() } ?: run {
            _pendingNavigation.value = null
            return
        }
        _pendingNavigation.value = PendingLinkNavigation(publicChannelUsername = normalizedUsername)
    }

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