package id.ac.ubharajaya.panicbutton

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException

object NotificationSender {
    private val client = OkHttpClient.Builder()
        .build()
    private const val server = "https://ntfy.ubharajaya.ac.id"
    private const val topic = "panic-button"
    private const val TAG = "NotificationSender"

    private fun sanitizeHeaderValue(value: String): String {
        val sb = StringBuilder()
        for (ch in value) {
            val code = ch.code
            if (code in 32..126) sb.append(ch)
        }
        val out = sb.toString()
        return if (out.isBlank()) "Alert" else out
    }

    suspend fun sendNotification(message: String): String = withContext(Dispatchers.IO) {
        try {
            val url = "$server/$topic"
            Log.d(TAG, "Preparing notification to $url")

            // Title ONLY has emoji
            val titleSafe = sanitizeHeaderValue("🚨 Alert 🚨")

            // Body is clean text, no emoji auto-append
            val cleanMessage = message.trim()

            val body = cleanMessage.toRequestBody("text/plain".toMediaType())

            val request = Request.Builder()
                .url(url)
                .addHeader("Title", titleSafe)
                .addHeader("Priority", "urgent")
                .addHeader("Tags", "warning")
                .post(body)
                .build()

            // Debug logging
            Log.d(TAG, "Body to send: $cleanMessage")

            client.newCall(request).execute().use { resp ->
                val respCode = resp.code
                val respMessage = resp.message
                val respBody = try {
                    resp.body?.string()
                } catch (e: Exception) {
                    null
                }

                Log.d(TAG, "Response: code=$respCode message=$respMessage body=$respBody")

                return@withContext if (resp.isSuccessful) {
                    "Notifikasi berhasil dikirim!"
                } else {
                    "Gagal mengirim notifikasi: $respCode $respMessage ${respBody ?: ""}".trim()
                }
            }

        } catch (e: IOException) {
            Log.e(TAG, "IO error", e)
            return@withContext "Gagal mengirim notifikasi: ${e.localizedMessage}"
        } catch (e: Exception) {
            Log.e(TAG, "Unexpected error", e)
            return@withContext "Gagal mengirim notifikasi: ${e.localizedMessage}"
        }
    }
}
