package io.stellarfrontier.stellarplugin.commands

import com.google.gson.Gson
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.bukkit.ChatColor
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import java.io.IOException

class LinkCommand : CommandExecutor {
    private val client = OkHttpClient()
    private val gson = Gson()
    private val JSON = "application/json; charset=utf-8".toMediaType()

    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
        if (sender !is Player) {
            sender.sendMessage("Only players can use this command.")
            return true
        }

        if (args.isEmpty()) {
            sender.sendMessage("${ChatColor.RED}Usage: /link <code>")
            return true
        }

        val code = args[0]
        val data = mapOf(
            "code" to code,
            "uuid" to sender.uniqueId.toString(),
            "username" to sender.name
        )

        val body = gson.toJson(data).toRequestBody(JSON)
        val request = Request.Builder()
            .url("http://localhost:5000/api/link") // TODO: Configurable URL
            .post(body)
            .build()

        // Execute async to avoid blocking main thread
        // In a real plugin, use BukkitScheduler.runTaskAsynchronously
        Thread {
            try {
                client.newCall(request).execute().use { response ->
                    if (response.isSuccessful) {
                        sender.sendMessage("${ChatColor.GREEN}Account linked successfully!")
                    } else {
                        sender.sendMessage("${ChatColor.RED}Failed to link account: ${response.message}")
                    }
                }
            } catch (e: IOException) {
                sender.sendMessage("${ChatColor.RED}Error connecting to web server.")
                e.printStackTrace()
            }
        }.start()

        return true
    }
}
