package com.correx.core.tasks

import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.TaskCreatedEvent
import com.correx.core.sessions.projections.Projection

/**
 * Counts created tasks in a project stream. The numeric suffix of a human key
 * (`<prefix>-<n>`) is taken from this count, so ids never collide even after a task is
 * cancelled — it counts creations, not currently-live tasks.
 */
class TaskCounterProjection(
    private val projectId: String,
) : Projection<TaskCounterState> {

    override fun initial(): TaskCounterState =
        TaskCounterState(projectId, 0)

    override fun apply(
        state: TaskCounterState,
        event: StoredEvent,
    ): TaskCounterState =
        if (event.payload is TaskCreatedEvent) state.copy(count = state.count + 1) else state
}
