// android/src/main/kotlin/com/complycube/flutter/complycube/events/EventJson.kt package com.complycube.reactnative.events import org.json.JSONObject import com.complycube.sdk.analytics.service.AnalyticsEvent object EventJson { fun success(payload: Any?): String = JSONObject() .put("type", "success") .put("payload", payload ?: JSONObject.NULL) .toString() fun cancelled(code: String? = null, reason: String? = null): String = JSONObject() .put("type", "cancelled") .apply { if (!code.isNullOrBlank()) put("code", code) if (!reason.isNullOrBlank()) put("reason", reason) } .toString() fun error(codeAny: Any?, message: String?, details: Any? = null): String { val code = normalizeCode(codeAny) return JSONObject() .put("type", "error") .put("code", code ?: "UNKNOWN") .put("message", message ?: "Unexpected error") .apply { if (details != null) put("details", details) if (codeAny != null && code == null) put("rawCode", codeAny.toString()) } .toString() } fun custom(event: AnalyticsEvent?): String = JSONObject() .put("type", "custom") .put("event", event.toString()) .toString() // --- helpers --- private fun normalizeCode(codeAny: Any?): String? { if (codeAny == null) return null // Prefer enum.name if available; otherwise fallback to toString sanitized. val raw = codeAny.toString().trim() // Strip Kotlin enum toString like FOO(bar) or $FOO@123 val snake = raw .replace(Regex("""^.*\$([A-Z0-9_]+)@.*$"""), "$1") .replace(Regex("""[^A-Za-z0-9_]+"""), "_") .trim('_') .uppercase() return if (snake.isBlank()) null else snake } }