package com.correx.apps.server.routes

import com.correx.apps.server.ServerModule
import com.correx.core.events.events.ClarificationAnswer
import com.correx.core.events.types.SessionId
import com.correx.core.utils.TypeId
import io.ktor.http.HttpStatusCode
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.post
import kotlinx.serialization.Serializable

// REST parity for stage clarifications (WS already has ClientMessage.ClarificationResponse). Keyed by
// session — the server resolves the live pending (stageId, requestId) so a headless run (a script,
// `correx run`) can clear a discovery-stage clarification without a WebSocket. If the caller omits the
// answer for a question, its value is the empty string (free-text skip). Fixes Vikunja #42.
@Serializable
data class ClarifyStageRequest(val answers: List<ClarificationAnswer>)

internal fun Route.clarifyStageRoute(module: ServerModule) {
    post("/clarify") {
        val id = call.parameters["id"]
        if (id == null) {
            call.respond(HttpStatusCode.BadRequest, "Missing session id")
            return@post
        }
        val sessionId: SessionId = TypeId(id)
        val pending = module.orchestrator.pendingClarificationFor(sessionId)
        if (pending == null) {
            call.respond(HttpStatusCode.NotFound, "No pending clarification for session $id")
            return@post
        }
        val answers = call.receive<ClarifyStageRequest>().answers
        module.orchestrator.submitClarification(sessionId, pending.stageId, pending.requestId, answers)
        call.respond(HttpStatusCode.OK)
    }
}
