package dev.inmo.postssystem.client.ui.fsm

import dev.inmo.postssystem.features.auth.client.AuthUnavailableException
import dev.inmo.micro_utils.fsm.common.*

interface   UIFSMHandler<T : UIFSMState> : StatesHandler<T, UIFSMState> {
    suspend fun StatesMachine<in UIFSMState>.safeHandleState(state: T): UIFSMState?
    override suspend fun StatesMachine<in UIFSMState>.handleState(state: T): UIFSMState? {
        return runCatching {
            safeHandleState(state).also(::println)
        }.getOrElse {
            errorToNextStep(state, it) ?.let { return it } ?: throw it
        }.also(::println)
    }

    suspend fun errorToNextStep(
        currentState: T,
        e: Throwable
    ): UIFSMState? = when (e) {
        is AuthUnavailableException -> if (currentState is AuthUIFSMState) {
            currentState
        } else {
            AuthUIFSMState(currentState)
        }
        else -> null
    }
}
