package com.correx.core.events.serialization

import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.WorkspaceStateObservedEvent
import com.correx.core.events.types.SessionId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class WorkspaceStateObservedEventSerializationTest {

    @Test
    fun `WorkspaceStateObservedEvent round-trips as polymorphic EventPayload`() {
        val sample: EventPayload = WorkspaceStateObservedEvent(
            sessionId = SessionId("s1"),
            workspaceRoot = "/home/user/project",
            stateKey = "git:abc1234",
            source = "git",
            branch = "main",
            dirty = false,
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        assertTrue(encoded.contains("\"type\":\"WorkspaceStateObserved\""), "SerialName must be present: $encoded")
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(), encoded))
    }

    @Test
    fun `fingerprint source without branch round-trips`() {
        val sample: EventPayload = WorkspaceStateObservedEvent(
            sessionId = SessionId("s2"),
            workspaceRoot = "/repo",
            stateKey = "fp:9f8e7d",
            source = "fingerprint",
        )
        assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(),
            eventJson.encodeToString(EventPayload.serializer(), sample)))
    }

    @Test
    fun `dirty git workspace round-trips with dirty flag`() {
        val sample: EventPayload = WorkspaceStateObservedEvent(
            sessionId = SessionId("s3"),
            workspaceRoot = "/dirty/repo",
            stateKey = "fp:deadbeef",
            source = "fingerprint",
            branch = "feature",
            dirty = true,
        )
        val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
        val decoded = eventJson.decodeFromString(EventPayload.serializer(), encoded) as WorkspaceStateObservedEvent
        assertEquals(true, decoded.dirty)
        assertNull(null) // branch can be non-null
    }
}
