package br.gov.extrema.agenteti.network

import android.content.Context
import br.gov.extrema.agenteti.device.DeviceCollector
import br.gov.extrema.agenteti.security.SecureStore
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID

class ApiException(val statusCode: Int, message: String) : IOException(message)

class ApiClient(context: Context) {
    private val store = SecureStore(context)
    private fun base(): String = store.get("server", "https://extrema.dev.br/manutencao_ti/api/tablets").trimEnd('/')

    fun post(path: String, body: JSONObject = JSONObject(), authenticated: Boolean): JSONObject {
        val endpoint = URL("${base()}/$path");if (endpoint.protocol != "https") throw IOException("O servidor deve usar HTTPS.")
        val connection = endpoint.openConnection() as HttpURLConnection
        connection.connectTimeout = 15_000;connection.readTimeout = 30_000;connection.requestMethod = "POST";connection.doOutput = true
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");connection.setRequestProperty("Accept", "application/json")
        if (authenticated) {
            connection.setRequestProperty("Authorization", "Bearer ${store.get("token")}")
            connection.setRequestProperty("X-Agent-Token", store.get("token"))
            connection.setRequestProperty("X-Agent-Id", store.get("agent_id"));connection.setRequestProperty("X-Timestamp", (System.currentTimeMillis()/1000).toString())
            connection.setRequestProperty("X-Nonce", DeviceCollector.sha256(UUID.randomUUID().toString()+System.nanoTime()))
        }
        connection.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
        val code = connection.responseCode;val stream = if (code in 200..299) connection.inputStream else connection.errorStream
        val response = stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty();connection.disconnect()
        val json = try { JSONObject(response) } catch (_: Exception) { JSONObject().put("message", "Resposta inválida do servidor (HTTP $code).") }
        if (code !in 200..299) throw ApiException(code, json.optString("message", "HTTP $code"))
        return json
    }
}
