package pt.whatsms.gateway.modules.gateway

import pt.whatsms.gateway.modules.settings.Exporter
import pt.whatsms.gateway.modules.settings.Importer
import pt.whatsms.gateway.modules.settings.KeyValueStorage
import pt.whatsms.gateway.modules.settings.get

class GatewaySettings(
    private val storage: KeyValueStorage,
) : Exporter, Importer {
    enum class NotificationChannel {
        AUTO,
        SSE_ONLY,
    }

    var enabled: Boolean
        get() = storage.get<Boolean>(ENABLED) ?: false
        set(value) = storage.set(ENABLED, value)

    val deviceId: String?
        get() = registrationInfo?.id

    var registrationInfo: GatewayApi.DeviceRegisterResponse?
        get() = storage.get(REGISTRATION_INFO)
        set(value) = storage.set(REGISTRATION_INFO, value)

    var fcmToken: String?
        get() = storage.get(FCM_TOKEN)
        set(value) = storage.set(FCM_TOKEN, value)

    val username: String?
        get() = registrationInfo?.login
    val password: String?
        get() = registrationInfo?.password

    // WhatSMS fork: hardcoded server. Campo de URL removido do UI.
    val serverUrl: String
        get() = WHATSMS_SERVER_URL

    // WhatSMS fork: private token hardcoded para auto-registo sem configuração.
    // Token rotado periodicamente via rebuild do APK.
    val privateToken: String?
        get() = WHATSMS_PRIVATE_TOKEN

    val notificationChannel: NotificationChannel
        get() = storage.get<NotificationChannel>(NOTIFICATION_CHANNEL) ?: NotificationChannel.AUTO

    companion object {
        private const val REGISTRATION_INFO = "REGISTRATION_INFO"
        private const val ENABLED = "ENABLED"
        private const val FCM_TOKEN = "fcm_token"

        private const val CLOUD_URL = "cloud_url"
        private const val PRIVATE_TOKEN = "private_token"
        private const val NOTIFICATION_CHANNEL = "notification_channel"

        // WhatSMS fork: servidor da Descomplicar.
        const val WHATSMS_SERVER_URL = "https://smsgw.whatsms.pt/api/mobile/v1"

        // WhatSMS fork: private_token do GATEWAY_TOKEN config do server.
        // Permite auto-registo silencioso de novos devices.
        const val WHATSMS_PRIVATE_TOKEN =
            "a6c877b0369bd68d77c1760a88ec1996c6b672353f4b6344"
    }

    override fun export(): Map<String, *> {
        return mapOf(
            CLOUD_URL to serverUrl,
            NOTIFICATION_CHANNEL to notificationChannel.name,
        )
    }

    override fun import(data: Map<String, *>): Boolean {
        return data.map {
            when (it.key) {
                CLOUD_URL -> {
                    val url = it.value?.toString() ?: WHATSMS_SERVER_URL
                    if (url != null && !url.startsWith("https://")) {
                        throw IllegalArgumentException("url must start with https://")
                    }

                    val changed = serverUrl != url

                    storage.set(it.key, url)

                    changed
                }

                PRIVATE_TOKEN -> {
                    val newValue = it.value?.toString()
                    val changed = privateToken != newValue

                    storage.set(it.key, newValue)

                    changed
                }

                NOTIFICATION_CHANNEL -> {
                    val newValue = it.value?.let { NotificationChannel.valueOf(it.toString()) }
                        ?: NotificationChannel.AUTO
                    val changed = notificationChannel != newValue

                    storage.set(it.key, newValue.name)

                    changed
                }

                else -> false
            }
        }.any { it }
    }
}
