package com.rosetta.messenger.session

import com.rosetta.messenger.data.DecryptedAccount
import kotlinx.coroutines.flow.StateFlow

sealed interface SessionState {
    data object LoggedOut : SessionState
    data class AuthInProgress(
        val publicKey: String? = null,
        val reason: String = ""
    ) : SessionState
    data class Ready(
        val account: DecryptedAccount,
        val reason: String = ""
    ) : SessionState
}

/**
 * Single source of truth for app-level auth/session lifecycle.
 * UI should rely on this state instead of scattering account checks.
 */
object AppSessionCoordinator {
    val sessionState: StateFlow<SessionState> = SessionStore.state

    fun dispatch(action: SessionAction) {
        SessionStore.dispatch(action)
    }

    fun markLoggedOut(reason: String = "") {
        dispatch(SessionAction.LoggedOut(reason = reason))
    }

    fun markAuthInProgress(publicKey: String? = null, reason: String = "") {
        dispatch(
            SessionAction.AuthInProgress(
                publicKey = publicKey,
                reason = reason
            )
        )
    }

    fun markReady(account: DecryptedAccount, reason: String = "") {
        dispatch(SessionAction.Ready(account = account, reason = reason))
    }

    fun syncFromCachedAccount(account: DecryptedAccount?) {
        dispatch(SessionAction.SyncFromCachedAccount(account = account))
    }
}
