package com.bytelyst.platform

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.net.URLEncoder

/**
 * Kill switch client for platform-service.
 *
 * Checks GET /api/settings/kill-switch to determine if the app should be disabled.
 * Fail-open: returns [KillSwitchResult.ok] on any error.
 *
 * Mirrors the Swift BLKillSwitchClient API.
 */
class BLKillSwitchClient(
    private val config: BLPlatformConfig,
) {
    @Serializable
    data class KillSwitchResult(
        val disabled: Boolean = false,
        val message: String? = null,
    ) {
        companion object {
            fun ok() = KillSwitchResult(disabled = false, message = null)
        }
    }

    private val json = Json { ignoreUnknownKeys = true }
    private val client = BLPlatformClient(config)

    /**
     * Check if the app is disabled. Fail-open on any error.
     */
    suspend fun check(): KillSwitchResult {
        return try {
            val enc = { v: String -> URLEncoder.encode(v, "UTF-8") }
            val response = client.request("GET", "/api/settings/kill-switch?productId=${enc(config.productId)}&platform=${enc(config.platform)}", skipAuth = true)
            json.decodeFromString<KillSwitchResult>(response)
        } catch (_: Exception) {
            KillSwitchResult.ok()
        }
    }
}
