package com.correx.core.events.serialization

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.ToolInvocationId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class FileWrittenEventSerializationTest {

    private val sample = FileWrittenEvent(
        invocationId = ToolInvocationId("inv-1"),
        sessionId = SessionId("sess-1"),
        path = "src/Main.kt",
        preImageHash = "aaaa",
        postImageHash = "bbbb",
        preExisted = true,
        mode = "0644",
        timestampMs = 7L,
    )

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

    @Test
    fun `decodes hand-written FileWritten JSON for a new file`() {
        val json = """
            {"type":"FileWritten","invocationId":"inv-9","sessionId":"s","path":"new.txt",
             "postImageHash":"cccc","preExisted":false,"timestampMs":1}
        """.trimIndent()
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), json)
        assertTrue(decoded is FileWrittenEvent)
        decoded as FileWrittenEvent
        assertEquals(false, decoded.preExisted)
        assertEquals(null, decoded.preImageHash)
        assertEquals("cccc", decoded.postImageHash)
    }
}
