package com.correx.core.artifacts

import com.correx.core.events.events.StoredEvent
import com.correx.core.sessions.projections.Projection
import java.util.logging.*

class ArtifactProjector(private val reducer: ArtifactReducer) : Projection<ArtifactState> {

    private val logger: Logger = Logger.getLogger(ArtifactProjector::class.java.name)

    override fun initial(): ArtifactState = ArtifactState()

    // Invalid lifecycle transitions must not crash the replayer. Log and leave state unchanged
    // so replay continues; the event log remains the source of truth.
    override fun apply(state: ArtifactState, event: StoredEvent): ArtifactState =
        reducer.reduce(state, event).getOrElse { exception ->
            if (exception !is IllegalStateException) throw exception
            logger.warning(
                "Invalid artifact lifecycle transition (event payload=${event.payload::class.simpleName}): " +
                    "${exception.message}. State unchanged."
            )
            state
        }
}
