package com.correx.apps.server.tasks

import com.correx.core.events.stores.EventStore
import com.correx.core.sessions.SessionSummaryProjector
import com.correx.core.tasks.ResolvedSession
import com.correx.core.tasks.TaskSessionResolver
import com.correx.core.utils.TypeId
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Resolves SESSION link targets for the task context bundle by projecting the session's events into
 * a [com.correx.core.sessions.SessionSummary] (status / intent / workflow). Returns null when the
 * session has no events — the link then stays a raw related link.
 */
class SessionSummaryTaskSessionResolver(
    private val eventStore: EventStore,
) : TaskSessionResolver {

    private val projector = SessionSummaryProjector()

    override suspend fun resolve(targetId: String): ResolvedSession? = withContext(Dispatchers.IO) {
        val sessionId = TypeId(targetId)
        val events = eventStore.read(sessionId)
        if (events.isEmpty()) return@withContext null
        val summary = projector.project(sessionId, events)
        ResolvedSession(
            status = summary.status,
            intent = summary.intent,
            workflowId = summary.workflowId,
        )
    }
}
