package com.correx.core.artifacts

import com.correx.core.artifacts.model.ArtifactRelationship
import com.correx.core.events.events.ArtifactCreatedEvent
import com.correx.core.events.events.ArtifactValidatedEvent
import com.correx.core.events.events.ArtifactValidatingEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.types.ArtifactLifecyclePhase

interface ArtifactReducer {
    fun reduce(state: ArtifactState, event: StoredEvent): Result<ArtifactState>
}

class DefaultArtifactReducer : ArtifactReducer {

    override fun reduce(state: ArtifactState, event: StoredEvent): Result<ArtifactState> =
        when (val p = event.payload) {
            is ArtifactCreatedEvent ->
                Result.success(state.copy(phase = ArtifactLifecyclePhase.CREATED))
            is ArtifactValidatingEvent ->
                transition(state, ArtifactLifecyclePhase.VALIDATING, ArtifactLifecyclePhase.CREATED)
            is ArtifactValidatedEvent ->
                transition(state, ArtifactLifecyclePhase.VALIDATED, ArtifactLifecyclePhase.VALIDATING)
            else -> Result.success(state)
        }

    private fun transition(
        state: ArtifactState,
        to: ArtifactLifecyclePhase,
        from: ArtifactLifecyclePhase,
    ): Result<ArtifactState> =
        if (state.phase == from) {
            Result.success(state.copy(phase = to))
        } else {
            Result.failure(
                IllegalStateException(
                    "Invalid artifact transition: ${state.phase} → $to (expected $from)"
                )
            )
        }
}
