package com.correx.core.sessions

import com.correx.core.events.events.InitialIntentEvent
import com.correx.core.events.events.OrchestrationPausedEvent
import com.correx.core.events.events.SessionNamedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.TransitionExecutedEvent
import com.correx.core.events.events.WorkflowCompletedEvent
import com.correx.core.events.events.WorkflowFailedEvent
import com.correx.core.events.events.WorkflowStartedEvent
import com.correx.core.events.types.SessionId

class SessionSummaryProjector {
    fun project(sessionId: SessionId, events: List<StoredEvent>): SessionSummary {
        var intent: String? = null
        var name: String? = null
        var workflowId: String? = null
        var stageCount = 0
        var status = "UNKNOWN"
        val createdAt = events.firstOrNull()?.metadata?.timestamp
        val lastActivityAt = events.lastOrNull()?.metadata?.timestamp

        events.forEach { event ->
            when (val p = event.payload) {
                is InitialIntentEvent -> intent = p.intent
                is SessionNamedEvent -> name = p.name
                is WorkflowStartedEvent -> {
                    workflowId = p.workflowId
                    status = SessionStatus.ACTIVE.name
                }
                is TransitionExecutedEvent -> stageCount++
                is OrchestrationPausedEvent -> status = SessionStatus.PAUSED.name
                is WorkflowCompletedEvent -> status = SessionStatus.COMPLETED.name
                is WorkflowFailedEvent -> status = SessionStatus.FAILED.name
                else -> Unit
            }
        }

        return SessionSummary(
            sessionId = sessionId,
            name = name,
            intent = intent,
            workflowId = workflowId,
            status = status,
            createdAt = createdAt,
            lastActivityAt = lastActivityAt,
            stageCount = stageCount,
        )
    }
}
