package com.correx.core.transitions.mapper

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.StageCompletedEvent
import com.correx.core.events.events.StageFailedEvent
import com.correx.core.events.events.TransitionExecutedEvent
import com.correx.core.events.types.SessionId
import com.correx.core.transitions.execution.StageExecutionRequest
import com.correx.core.transitions.execution.StageExecutionResult

class DefaultStageExecutionEventMapper : StageExecutionEventMapper {

    override fun toEvents(
        request: StageExecutionRequest,
        result: StageExecutionResult
    ): List<EventPayload> {

        val baseTransition = TransitionExecutedEvent(
            sessionId = SessionId(request.sessionId),
            from = request.from,
            to = request.to,
            transitionId = request.transitionId
        )

        return when (result) {

            is StageExecutionResult.Success -> listOf(
                baseTransition,
                StageCompletedEvent(
                    sessionId = SessionId(request.sessionId),
                    stageId = request.to,
                    transitionId = request.transitionId
                )
            )

            is StageExecutionResult.Failure -> listOf(
                baseTransition,
                StageFailedEvent(
                    sessionId = SessionId(request.sessionId),
                    stageId = request.to,
                    transitionId = request.transitionId,
                    reason = result.reason
                )
            )
        }
    }
}
