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

/**
 * 多服务器容错推送：按列表顺序依次尝试，首个成功即止。
 * 全失败 → 返回最后一个错误；空列表 → "无可用服务器"。
 */
object BarkSender {
    suspend fun pushToFirst(servers: List<BarkServer>, msg: BarkMessage): Result<Unit> = withContext(Dispatchers.IO) {
        runCatching {
            require(servers.any()) { "无可用服务器" }
            var lastErr: Throwable? = null
            for (s in servers) {
                val r = BarkClient(s).push(msg)
                if (r.isSuccess) return@runCatching
                lastErr = r.exceptionOrNull()
            }
            throw lastErr ?: error("推送失败")
        }
    }
}
