package com.correx.core.sessions.projections

import com.correx.core.events.events.EgressHostsGrantedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.types.SessionId

/**
 * Folds the additional egress hosts granted to one session. State is the running union of every
 * [EgressHostsGrantedEvent.hosts] emitted for [sessionId]; grants are additive (set union) and
 * unrelated events — including grants for other sessions — are ignored. The resulting
 * `Set<String>` is the per-session input to
 * [com.correx.core.toolintent.rules.EgressAllowlist.isAllowed], unioned with the static
 * `networkAllowedHosts` at the network gate.
 */
class EgressAllowlistProjection(
    private val sessionId: SessionId,
) : Projection<Set<String>> {

    override fun initial(): Set<String> = emptySet()

    override fun apply(state: Set<String>, event: StoredEvent): Set<String> {
        val payload = event.payload
        return if (payload is EgressHostsGrantedEvent && payload.sessionId == sessionId) {
            state + payload.hosts
        } else {
            state
        }
    }
}
