package ru.forbion.f7cloud.mobile.ui

import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.network.NetworkFactory
import ru.forbion.f7cloud.core.network.UnauthorizedException
import ru.forbion.f7cloud.core.network.applyOcsJson

object AppMenuRepository {
    fun fetchExternalSites(session: AuthSession): List<AppMenuExternalSite> {
        val client = NetworkFactory.newAuthedClient(
            session.username,
            session.appPassword,
            session.trustAllCerts,
        )
        val url = "${session.serverUrl.trimEnd('/')}/ocs/v2.php/apps/external/api/v1?format=json"
        val request = Request.Builder().url(url).applyOcsJson().get().build()
        return runCatching {
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful || response.body == null) {
                    return emptyList()
                }
                val body = response.body!!.string()
                val array = when {
                    body.trimStart().startsWith("[") -> JSONArray(body)
                    else -> {
                        val data = JSONObject(body).optJSONObject("ocs")?.opt("data")
                        when (data) {
                            is JSONArray -> data
                            else -> JSONArray()
                        }
                    }
                }
                (0 until array.length()).mapNotNull { index ->
                    val site = array.optJSONObject(index) ?: return@mapNotNull null
                    val name = site.optString("name").ifBlank { return@mapNotNull null }
                    val icon = site.optString("icon").ifBlank { null }
                    val redirect = site.optInt("redirect", 0) == 1
                    val rawUrl = site.optString("url")
                    val siteId = site.optInt("id", -1)
                    val openUrl = when {
                        redirect && rawUrl.isNotBlank() -> rawUrl
                        siteId >= 0 -> "${session.serverUrl.trimEnd('/')}/index.php/apps/external/$siteId/"
                        rawUrl.isNotBlank() -> rawUrl
                        else -> return@mapNotNull null
                    }
                    AppMenuExternalSite(
                        name = name,
                        iconUrl = resolveExternalIcon(session.serverUrl, icon, name),
                        openUrl = openUrl,
                    )
                }
            }
        }.getOrDefault(emptyList())
    }

    /**
     * Иконка внешнего сайта. API external отдаёт `icon` как ИМЯ ФАЙЛА (напр. «bitrix24.png»),
     * а не URL — сайт грузит его с `/apps/external/img/{icon}` (см. layout.user.php). Раньше
     * имя файла бралось как есть → битая ссылка → глобус-заглушка у Bitrix/1C.
     */
    private fun resolveExternalIcon(serverUrl: String, icon: String?, name: String): String {
        val base = serverUrl.trimEnd('/')
        return when {
            icon.isNullOrBlank() -> "$base/index.php/apps/external/img/external.svg"
            icon.startsWith("http") -> icon
            icon.startsWith("/") -> "$base$icon"
            else -> "$base/index.php/apps/external/img/$icon"
        }
    }
}
