package top.r3944realms.ltdmanager.core.config

import top.r3944realms.ltdmanager.utils.CryptoUtil
import top.r3944realms.ltdmanager.utils.YamlUpdater

data class WhitelistSystemConfig(
    var url: String? = null,
    var encryptedToken: String? = null
) {
    val decryptedToken: String?
        get() {
            if (encryptedToken == null) return null
            if (!isEncrypted()) return encryptedToken
            return try {
                val cipherText = encryptedToken!!.substring(4, encryptedToken!!.length - 1)
                CryptoUtil.decrypt(cipherText)
            } catch (e: Exception) {
                throw IllegalStateException("Whitelist API token 解密失败", e)
            }
        }

    fun encryptToken() {
        if (encryptedToken == null || isEncrypted()) return
        try {
            encryptedToken = "ENC(${CryptoUtil.encrypt(encryptedToken!!)})"
            YamlUpdater.updateYaml(
                YamlConfigLoader.appConfigFilePath.toString(),
                "whitelist-system.encrypted-token",
                encryptedToken!!
            )
        } catch (e: Exception) {
            throw IllegalStateException("Whitelist API token 加密失败", e)
        }
    }

    private fun isEncrypted(): Boolean {
        return encryptedToken != null &&
                encryptedToken!!.startsWith("ENC(") &&
                encryptedToken!!.endsWith(")")
    }

    override fun toString(): String = "WhitelistSystemConfig(url=$url, token=***)"
}
