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

import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

/**
 * [FrameFields] does minimal typed reads from a raw SSE frame object for the
 * fields a `*.remove` / `*.decay` delta needs; it must return null (not crash) on
 * a missing or ill-typed field so a malformed frame is skipped.
 */
class FrameFieldsTest {

    @Test fun longFieldParsesNumericPrimitive() {
        val obj = buildJsonObject { put("serial", "12345") }
        assertEquals(12345L, FrameFields.longField(obj, "serial"))
    }

    @Test fun longFieldReturnsNullOnMissingOrNonNumeric() {
        val obj = buildJsonObject { put("serial", "0xNaN") }
        assertNull(FrameFields.longField(obj, "serial"))     // not a Long
        assertNull(FrameFields.longField(obj, "absent"))     // missing key
    }

    @Test fun longFieldReturnsNullOnJsonNullOrObject() {
        val obj = JsonObject(mapOf("a" to JsonNull, "b" to JsonObject(emptyMap())))
        assertNull(FrameFields.longField(obj, "a"))
        assertNull(FrameFields.longField(obj, "b"))
    }

    @Test fun stringFieldReadsPrimitiveContent() {
        val obj = JsonObject(mapOf("kind" to JsonPrimitive("champ.remove")))
        assertEquals("champ.remove", FrameFields.stringField(obj, "kind"))
        assertNull(FrameFields.stringField(obj, "missing"))
    }
}
