package ru.forbion.f7cloud.core.auth

import okhttp3.Request
import ru.forbion.f7cloud.core.network.NetworkFactory
import ru.forbion.f7cloud.core.network.UnauthorizedException
import ru.forbion.f7cloud.core.network.applyOcsJson
import ru.forbion.f7cloud.core.network.isOcsSuccess
import ru.forbion.f7cloud.core.network.ocsData
import ru.forbion.f7cloud.core.network.ocsMeta
import ru.forbion.f7cloud.core.network.parseJsonObject

object OcsUserResolver {
    fun resolveDavUserId(session: AuthSession): String {
        session.davUserId?.let { return it }
        val client = NetworkFactory.newAuthedClient(
            session.username,
            session.appPassword,
            session.trustAllCerts,
        )
        val request = Request.Builder()
            .url("${session.serverUrl.trimEnd('/')}/ocs/v2.php/cloud/user?format=json")
            .applyOcsJson()
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful || response.body == null) {
                error("User profile HTTP ${response.code}")
            }
            val root = parseJsonObject(response.body!!.string(), "профиль пользователя")
            val meta = root.ocsMeta()
            if (!isOcsSuccess(meta)) {
                error("User profile OCS error")
            }
            val id = root.ocsData()?.optString("id").orEmpty().trim()
            return id.ifBlank { session.username }
        }
    }
}
