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

import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject

/**
 * Parse a JSON-valued settings row, client side — the second stage of decoding
 * `nav_public` (THEMING_AND_NAV.md §3).
 *
 * The Kotlin counterpart to the web client's `lib/settingsJson.js`, and
 * deliberately the same three lines of judgement: `settings.value` is TEXT, so
 * the row arrives as a **string inside** the already-decoded settings object,
 * and a malformed or wrong-shaped one must read as **absent** — the surface
 * falls back to the coded default — never as an error and never as a
 * half-applied object.
 */
private val settingsJson = Json { ignoreUnknownKeys = true }

/**
 * @param raw the raw stored value, as it arrived in the settings payload
 * @return the parsed object, or null when absent/malformed
 */
fun parseJsonSetting(raw: String?): JsonObject? {
    if (raw.isNullOrEmpty()) return null
    val parsed = try {
        settingsJson.parseToJsonElement(raw)
    } catch (_: SerializationException) {
        return null
    }
    // Only plain objects. A stored `null`, `4`, `"x"` or array is as unusable to
    // every consumer of these keys as a syntax error is.
    return parsed as? JsonObject
}
