/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.core.net

import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

/**
 * Unit tests for SSE frame parsing (PLAN.md §6.2). The reconnect/backoff loop and
 * OkHttp EventSource wiring are integration concerns; the pure parse of a `data:`
 * payload into `(kind, object)` is unit-testable here.
 */
class ShardStreamClientTest {

    private val client = ShardStreamClient(
        baseClient = OkHttpClient(),
        baseUrlHolder = BaseUrlHolder(),
        json = Json { ignoreUnknownKeys = true },
    )

    @Test fun parsesKindAndKeepsObject() {
        val parsed = client.parseFrame("""{"kind":"champ.update","serial":5,"status":"active"}""")
        assertEquals("champ.update", parsed?.first)
        assertEquals("5", parsed?.second?.get("serial").toString())
    }

    @Test fun dropsKeepaliveComment() {
        assertNull(client.parseFrame(": ping"))
        assertNull(client.parseFrame(": connected"))
    }

    @Test fun dropsBlank() {
        assertNull(client.parseFrame("   "))
        assertNull(client.parseFrame(""))
    }

    @Test fun dropsFrameWithoutKind() {
        assertNull(client.parseFrame("""{"serial":5}"""))
    }

    @Test fun dropsNullKind() {
        assertNull(client.parseFrame("""{"kind":null}"""))
    }

    @Test fun dropsMalformedJson() {
        assertNull(client.parseFrame("""{"kind":"x" """))
        assertNull(client.parseFrame("not json"))
    }
}
