package com.correx.core.transitions.resolution

import com.correx.core.transitions.evaluation.EvaluationContext
import com.correx.core.transitions.evaluation.TransitionConditionEvaluator
import com.correx.core.transitions.graph.WorkflowGraph

class DefaultTransitionResolver(
    private val evaluator: TransitionConditionEvaluator
) : TransitionResolver {

    @Suppress("ReturnCount", "TooGenericExceptionCaught")
    override fun resolve(
        graph: WorkflowGraph,
        context: EvaluationContext
    ): TransitionDecision {
        val outgoing = graph.transitions
            .asSequence()
            .filter { it.from == context.currentStage }
            .sortedWith(TransitionOrdering.comparator)
            .toList()

        if (outgoing.isEmpty()) return TransitionDecision.NoMatch

        for (edge in outgoing) {
            val result = try {
                evaluator.evaluate(edge.condition, context)
            } catch (e: Exception) {
                return TransitionDecision.Blocked(
                    "condition evaluation failed on '${edge.id.value}': ${e.message}",
                )
            }
            if (result) {
                return TransitionDecision.Move(
                    transitionId = edge.id,
                    to = edge.to
                )
            }
        }
        return TransitionDecision.Stay
    }
}
