package com.correx.core.events.serialization

import com.correx.core.events.events.BriefEchoMismatchEvent
import com.correx.core.events.events.EventPayload
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 BriefEchoMismatchEventSerializationTest {

    private val sample = BriefEchoMismatchEvent(
        sessionId = SessionId("sess-1"),
        stageId = StageId("brief_echo"),
        uncoveredRequirements = listOf("must support retries", "must emit an event"),
        hallucinatedFiles = listOf("core/ghost/Phantom.kt"),
        hallucinatedSymbols = listOf("GhostService"),
    )

    @Test
    fun `round-trips as polymorphic EventPayload`() {
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        assertTrue(encoded.contains("\"type\":\"BriefEchoMismatch\""), "SerialName must be present: $encoded")
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded)
        assertEquals(sample, decoded)
    }

    @Test
    fun `decodes hand-written BriefEchoMismatch JSON`() {
        val json = """
            {"type":"BriefEchoMismatch","sessionId":"s","stageId":"brief_echo",
             "uncoveredRequirements":["req-1"],"hallucinatedFiles":["a/b.kt"],"hallucinatedSymbols":[]}
        """.trimIndent()
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), json)
        assertTrue(decoded is BriefEchoMismatchEvent)
        val event = decoded as BriefEchoMismatchEvent
        assertEquals(listOf("req-1"), event.uncoveredRequirements)
        assertEquals(listOf("a/b.kt"), event.hallucinatedFiles)
        assertTrue(event.hallucinatedSymbols.isEmpty())
    }

    @Test
    fun `empty lists round-trip correctly`() {
        val empty = sample.copy(
            uncoveredRequirements = emptyList(),
            hallucinatedFiles = emptyList(),
            hallucinatedSymbols = emptyList(),
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), empty)
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded)
        assertEquals(empty, decoded)
    }
}
