package com.a2i.forwarder.core

import com.a2i.forwarder.model.BarkMessage
import com.a2i.forwarder.model.BarkServer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit

class BarkClient(private val server: BarkServer) {
    private val json = Json { encodeDefaults = false; ignoreUnknownKeys = true }
    private val http = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(15, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build()

    suspend fun push(msg: BarkMessage): Result<Unit> = withContext(Dispatchers.IO) {
        runCatching {
            require(server.deviceKey.isNotBlank()) { "device key 为空" }
            val body = json.encodeToString(msg).toRequestBody(JSON)
            val url = server.server.trim().removeSuffix("/") + "/push"
            val req = Request.Builder().url(url).post(body).build()
            http.newCall(req).execute().use { res ->
                if (!res.isSuccessful) error("HTTP ${res.code}")
            }
        }
    }

    companion object {
        private val JSON = "application/json; charset=utf-8".toMediaType()
    }
}
