package com.rosetta.messenger.session

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

/**
 * Single runtime source of truth for session lifecycle state.
 * State transitions are produced only by SessionReducer.
 */
object SessionStore {
    private val _state = MutableStateFlow<SessionState>(SessionState.LoggedOut)
    val state: StateFlow<SessionState> = _state.asStateFlow()

    private val lock = Any()

    fun dispatch(action: SessionAction) {
        synchronized(lock) {
            _state.value = SessionReducer.reduce(_state.value, action)
        }
        syncIdentity(action)
    }

    private fun syncIdentity(action: SessionAction) {
        when (action) {
            is SessionAction.LoggedOut -> {
                IdentityStore.markLoggedOut(reason = action.reason)
            }
            is SessionAction.AuthInProgress -> {
                IdentityStore.markAuthInProgress(
                    publicKey = action.publicKey,
                    reason = action.reason
                )
            }
            is SessionAction.Ready -> {
                IdentityStore.setAccount(
                    account = action.account,
                    reason = action.reason
                )
            }
            is SessionAction.SyncFromCachedAccount -> {
                val account = action.account
                if (account == null) {
                    IdentityStore.markLoggedOut(reason = "cached_account_cleared")
                } else {
                    IdentityStore.setAccount(account = account, reason = "cached")
                }
            }
        }
    }
}
