package com.bytelyst.platform

import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
import java.net.URLEncoder

/**
 * License client for platform-service.
 *
 * Activates and checks license keys via /api/licenses endpoints.
 * URL-encodes the license key in the path to handle special characters.
 *
 * Mirrors the Swift BLLicenseClient API.
 */
class BLLicenseClient(
    private val config: BLPlatformConfig,
    private val tokenProvider: () -> String? = { null },
) {
    @Serializable
    data class LicenseStatus(
        val valid: Boolean = false,
        val plan: String = "free",
        val expiresAt: String? = null,
        val message: String? = null,
    )

    @Serializable
    data class ActivationResult(
        val success: Boolean = false,
        val plan: String = "free",
        val message: String? = null,
    )

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

    /**
     * Activate a license key.
     */
    suspend fun activate(licenseKey: String): ActivationResult {
        return try {
            val encoded = URLEncoder.encode(licenseKey, "UTF-8")
            val body = json.encodeToString(
                MapSerializer(String.serializer(), String.serializer()),
                mapOf("productId" to config.productId),
            )
            val response = client.request("POST", "/api/licenses/$encoded/activate", body)
            json.decodeFromString<ActivationResult>(response)
        } catch (e: Exception) {
            ActivationResult(success = false, message = e.message)
        }
    }

    /**
     * Check the status of a license key.
     */
    suspend fun checkStatus(licenseKey: String): LicenseStatus {
        return try {
            val encoded = URLEncoder.encode(licenseKey, "UTF-8")
            val response = client.request("GET", "/api/licenses/$encoded/status")
            json.decodeFromString<LicenseStatus>(response)
        } catch (e: Exception) {
            LicenseStatus(valid = false, message = e.message)
        }
    }

    /**
     * Deactivate a license key.
     */
    suspend fun deactivate(licenseKey: String): Boolean {
        return try {
            val encoded = URLEncoder.encode(licenseKey, "UTF-8")
            client.request("POST", "/api/licenses/$encoded/deactivate")
            true
        } catch (_: Exception) {
            false
        }
    }
}
