package ru.forbion.f7cloud.core.network

import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject

fun Request.Builder.applyOcsJson(): Request.Builder =
    header("OCS-APIRequest", "true")
        .header("Accept", "application/json")

fun parseJsonObject(body: String, what: String = "ответ сервера"): JSONObject {
    val trimmed = body.trim()
    if (trimmed.isEmpty()) {
        error("Пустой $what")
    }
    if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
        error("Сервер вернул XML вместо JSON ($what)")
    }
    return try {
        JSONObject(trimmed)
    } catch (e: Exception) {
        throw IllegalStateException("Некорректный JSON ($what)", e)
    }
}

fun parseJsonArray(body: String, what: String = "ответ сервера"): JSONArray {
    val trimmed = body.trim()
    if (trimmed.isEmpty()) {
        error("Пустой $what")
    }
    if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
        error("Сервер вернул XML вместо JSON ($what)")
    }
    return try {
        JSONArray(trimmed)
    } catch (e: Exception) {
        throw IllegalStateException("Некорректный JSON ($what)", e)
    }
}

fun JSONObject.ocsMeta(): JSONObject? = optJSONObject("ocs")?.optJSONObject("meta")

fun JSONObject.ocsData(): JSONObject? = optJSONObject("ocs")?.optJSONObject("data")

/** OCS v1 uses statuscode 100; OCS v2 uses meta.status "ok" or HTTP-style 200–299. */
fun isOcsSuccess(meta: JSONObject?): Boolean {
    if (meta == null) return false
    if (meta.optString("status") == "ok") return true
    val code = meta.optInt("statuscode", 0)
    return code == 100 || code in 200..299
}
