package com.mhss.app.mybrain.presentation.admin import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import java.net.HttpURLConnection import java.net.URI object AdminBackendService { var BASE_URL: String = "https://api.tgbotbuilder.com/api/v1" private val jsonHelper = Json { ignoreUnknownKeys = true } suspend fun login(email: String, password: String): Result> = withContext(Dispatchers.Default) { try { val payload = """{"email": "$email", "password": "$password"}""" val res = makeHttpRequest("POST", "/admin/auth/login", payload) val json = jsonHelper.parseToJsonElement(res).jsonObject val data = json["data"]?.jsonObject ?: throw Exception("Invalid response structure") val token = data["token"]?.jsonPrimitive?.content ?: throw Exception("Missing token") val adminName = data["admin_name"]?.jsonPrimitive?.content ?: "Platform Administrator" Result.success(Pair(token, adminName)) } catch (e: Exception) { Result.failure(e) } } suspend fun loginWithGoogle(email: String, fullName: String, idToken: String? = null): Result> = withContext(Dispatchers.Default) { try { val tokenPart = if (!idToken.isNullOrBlank()) """, "id_token": "${idToken.trim()}"""" else "" val payload = """{"email": "${email.trim()}", "full_name": "${fullName.trim()}"$tokenPart}""" val res = makeHttpRequest("POST", "/admin/auth/google", payload) val json = jsonHelper.parseToJsonElement(res).jsonObject val data = json["data"]?.jsonObject ?: throw Exception(json["detail"]?.jsonPrimitive?.content ?: "Access denied") val token = data["token"]?.jsonPrimitive?.content ?: throw Exception("Missing token") val adminName = data["admin_name"]?.jsonPrimitive?.content ?: "Platform Administrator" Result.success(Pair(token, adminName)) } catch (e: Exception) { Result.failure(e) } } suspend fun getOverview(token: String): Result = withContext(Dispatchers.Default) { try { val res = makeHttpRequest("GET", "/admin/overview", authToken = token) val json = jsonHelper.parseToJsonElement(res).jsonObject val dataObj = json["data"]?.jsonObject ?: throw Exception("No data object") val overview = jsonHelper.decodeFromString(dataObj.toString()) Result.success(overview) } catch (e: Exception) { Result.failure(e) } } suspend fun getUsers(token: String, limit: Int = 100): Result> = withContext(Dispatchers.Default) { try { val res = makeHttpRequest("GET", "/admin/users?limit=$limit", authToken = token) val json = jsonHelper.parseToJsonElement(res).jsonObject val dataArr = json["data"]?.jsonArray ?: throw Exception("No users array") val users = jsonHelper.decodeFromString>(dataArr.toString()) Result.success(users) } catch (e: Exception) { Result.failure(e) } } suspend fun updateUserPlan(token: String, userId: String, plan: String): Result = withContext(Dispatchers.Default) { try { val payload = """{"plan": "$plan"}""" makeHttpRequest("POST", "/admin/users/$userId/plan", payload, authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun updateUserStatus(token: String, userId: String, status: String): Result = withContext(Dispatchers.Default) { try { val payload = """{"status": "$status"}""" makeHttpRequest("POST", "/admin/users/$userId/status", payload, authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun deleteUser(token: String, userId: String): Result = withContext(Dispatchers.Default) { try { makeHttpRequest("DELETE", "/admin/users/$userId", authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun getBots(token: String, limit: Int = 100): Result> = withContext(Dispatchers.Default) { try { val res = makeHttpRequest("GET", "/admin/bots?limit=$limit", authToken = token) val json = jsonHelper.parseToJsonElement(res).jsonObject val dataArr = json["data"]?.jsonArray ?: throw Exception("No bots array") val bots = jsonHelper.decodeFromString>(dataArr.toString()) Result.success(bots) } catch (e: Exception) { Result.failure(e) } } suspend fun executeBotAction(token: String, botId: String, action: String): Result = withContext(Dispatchers.Default) { try { val payload = """{"action": "$action"}""" makeHttpRequest("POST", "/admin/bots/$botId/action", payload, authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun broadcastAnnouncement(token: String, title: String, message: String): Result = withContext(Dispatchers.Default) { try { val safeTitle = title.replace("\"", "\\\"") val safeMsg = message.replace("\"", "\\\"").replace("\n", "\\n") val payload = """{"title": "$safeTitle", "message": "$safeMsg"}""" makeHttpRequest("POST", "/admin/broadcast", payload, authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun getConfig(token: String): Result = withContext(Dispatchers.Default) { try { val res = makeHttpRequest("GET", "/admin/config", authToken = token) val json = jsonHelper.parseToJsonElement(res).jsonObject val dataObj = json["data"]?.jsonObject ?: throw Exception("No config") val cfg = jsonHelper.decodeFromString(dataObj.toString()) Result.success(cfg) } catch (e: Exception) { Result.failure(e) } } suspend fun updateConfig(token: String, config: AdminAppConfig): Result = withContext(Dispatchers.Default) { try { val payload = jsonHelper.encodeToString(AdminAppConfig.serializer(), config) makeHttpRequest("POST", "/admin/config", payload, authToken = token) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } suspend fun executeServerAction(token: String, action: String): Result = withContext(Dispatchers.Default) { try { val payload = """{"action": "$action"}""" val res = makeHttpRequest("POST", "/admin/server/action", payload, authToken = token) val json = jsonHelper.parseToJsonElement(res).jsonObject val msg = json["message"]?.jsonPrimitive?.content ?: "Action executed" Result.success(msg) } catch (e: Exception) { Result.failure(e) } } suspend fun updateFirebaseApiUrl(token: String, newUrl: String): Result = withContext(Dispatchers.Default) { try { val cleanUrl = newUrl.trim().removeSuffix("/") val payload = """{"api_url": "$cleanUrl"}""" makeHttpRequest("POST", "/admin/firebase/api-url", payload, authToken = token) BASE_URL = cleanUrl Result.success(cleanUrl) } catch (e: Exception) { Result.failure(e) } } private fun makeHttpRequest( method: String, path: String, body: String? = null, authToken: String? = null ): String { val url = URI("$BASE_URL$path").toURL() val conn = url.openConnection() as HttpURLConnection conn.requestMethod = method conn.connectTimeout = 12000 conn.readTimeout = 12000 conn.setRequestProperty("Content-Type", "application/json") conn.setRequestProperty("Accept", "application/json") if (!authToken.isNullOrBlank()) { conn.setRequestProperty("Authorization", "Bearer $authToken") } if (body != null && (method == "POST" || method == "PUT" || method == "PATCH")) { conn.doOutput = true conn.outputStream.use { os -> os.write(body.toByteArray(Charsets.UTF_8)) } } val code = conn.responseCode val stream = if (code in 200..299) conn.inputStream else conn.errorStream val response = stream?.bufferedReader()?.use { it.readText() } ?: "" if (code !in 200..299) { throw Exception("HTTP $code: $response") } return response } }