package de.trainingstagebuch.app.utils

import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

object JsonSafeUtils {
    private val parser = Json { ignoreUnknownKeys = true }

    fun parseObject(raw: String): JsonObject? {
        return runCatching { parser.parseToJsonElement(raw).jsonObject }.getOrNull()
    }

    fun getString(obj: JsonObject, vararg keys: String): String? {
        for (key in keys) {
            val value = obj[key]?.jsonPrimitive?.contentOrNull
            if (!value.isNullOrBlank()) return value
        }
        return null
    }

    fun getString(element: JsonElement?): String? {
        return runCatching { element?.jsonPrimitive?.contentOrNull }
            .getOrNull()
            ?.takeIf { it.isNotBlank() }
    }

    fun asArray(element: JsonElement?): List<JsonElement> {
        return (element as? kotlinx.serialization.json.JsonArray).orEmpty()
    }
}
