package com.correx.core.events.serialization

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.RepoKnowledgeHit
import com.correx.core.events.events.RepoKnowledgeRetrievedEvent
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class RepoKnowledgeRetrievedEventSerializationTest {

    @Test
    fun `RepoKnowledgeRetrievedEvent round-trips as polymorphic EventPayload`() {
        val sample: EventPayload = RepoKnowledgeRetrievedEvent(
            sessionId = SessionId("s"),
            stageId = StageId("impl"),
            query = "implement the parser",
            hits = listOf(RepoKnowledgeHit(path = "src/Parser.kt", text = "src/Parser.kt: Parser", score = 0.92f)),
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        assertTrue(encoded.contains("\"type\":\"RepoKnowledgeRetrieved\""), "SerialName must be present: $encoded")
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(), encoded))
    }

    @Test
    fun `empty hits list round-trips`() {
        val sample: EventPayload = RepoKnowledgeRetrievedEvent(
            sessionId = SessionId("s"),
            stageId = StageId("stage"),
            query = "some query",
            hits = emptyList(),
        )
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(),
            eventJson.encodeToString(EventPayload.serializer(), sample)))
    }

    @Test
    fun `multiple hits round-trip correctly`() {
        val sample: EventPayload = RepoKnowledgeRetrievedEvent(
            sessionId = SessionId("sess"),
            stageId = StageId("architect"),
            query = "context builder",
            hits = listOf(
                RepoKnowledgeHit(path = "core/context/ContextBuilder.kt", text = "class ContextBuilder", score = 0.95f),
                RepoKnowledgeHit(
                    path = "core/context/DefaultContextBuilder.kt",
                    text = "class DefaultContextBuilder",
                    score = 0.88f,
                ),
            ),
        )
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(),
            eventJson.encodeToString(EventPayload.serializer(), sample)))
    }
}
