package com.correx.core.events.serialization

import com.correx.core.events.events.BriefGroundingCheckedEvent
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.GroundingReference
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 BriefGroundingCheckedEventSerializationTest {

    private val sample = BriefGroundingCheckedEvent(
        sessionId = SessionId("sess-1"),
        stageId = StageId("analyst"),
        artifactId = "analyst",
        references = listOf(
            GroundingReference("core/validation/JsonSchemaValidator.kt", grounded = true),
            GroundingReference("core/ghost/Phantom.kt", grounded = false),
        ),
    )

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

    @Test
    fun `decodes hand-written BriefGroundingChecked JSON`() {
        val json = """
            {"type":"BriefGroundingChecked","sessionId":"s","stageId":"analyst","artifactId":"analyst",
             "references":[{"reference":"a/b.kt","grounded":false}]}
        """.trimIndent()
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), json)
        assertTrue(decoded is BriefGroundingCheckedEvent)
        assertEquals(false, (decoded as BriefGroundingCheckedEvent).references.single().grounded)
    }
}
