package com.correx.core.events.serialization

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.RepoMapComputedEvent
import com.correx.core.events.events.RepoMapEntry
import com.correx.core.events.types.SessionId
import kotlinx.datetime.Instant
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class RepoMapComputedEventSerializationTest {

    @Test
    fun `RepoMapComputedEvent with stateKey round-trips`() {
        val sample: EventPayload = RepoMapComputedEvent(
            sessionId = SessionId("s"),
            repoRoot = "/repo",
            entries = listOf(RepoMapEntry(path = "src/Foo.kt", score = 0.9)),
            computedAt = Instant.parse("2026-06-11T00:00:00Z"),
            stateKey = "git:abc123",
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        assertTrue(encoded.contains("\"stateKey\":\"git:abc123\""), "stateKey must be in JSON: $encoded")
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(), encoded))
    }

    @Test
    fun `RepoMapComputedEvent without stateKey field decodes with null`() {
        val json = """{"type":"RepoMapComputed","sessionId":"s","repoRoot":"/repo",""" +
            """"entries":[],"computedAt":"2026-06-11T00:00:00Z"}"""
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), json) as RepoMapComputedEvent
        assertNull(decoded.stateKey)
    }

    @Test
    fun `RepoMapComputedEvent with null stateKey round-trips`() {
        val sample: EventPayload = RepoMapComputedEvent(
            sessionId = SessionId("s"),
            repoRoot = "/repo",
            entries = emptyList(),
            computedAt = Instant.parse("2026-06-11T00:00:00Z"),
            stateKey = null,
        )
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(),
            eventJson.encodeToString(EventPayload.serializer(), sample)))
    }
}
