package com.centralcloud.oncall.app

import android.content.Context
import android.content.RestrictionsManager
import com.centralcloud.oncall.BuildConfig
import com.centralcloud.oncall.db.Repository
import com.centralcloud.oncall.sms.SmsRelayPreferences
import com.centralcloud.oncall.util.Log

/**
 * Applies centrally managed OnCall bootstrap configuration.
 *
 * Purpose: let Android Enterprise / managed Play installs point the forked app
 * at the organization-owned OnCall notification server before the responder
 * manually subscribes to any topic.
 *
 * Consumer: Application.onCreate during process startup.
 */
object OnCallManagedConfig {
    private const val TAG = "OnCallManagedConfig"
    private const val KEY_SERVER_URL = "oncall_server_url"
    private const val KEY_CONFIG_URL = "oncall_config_url"
    private const val KEY_ENROLLMENT_TOKEN = "oncall_enrollment_token"
    private const val KEY_ENVIRONMENT = "oncall_environment"

    fun apply(context: Context, repository: Repository) {
        val restrictions = context
            .getSystemService(RestrictionsManager::class.java)
            ?.applicationRestrictions

        val serverUrl = restrictions
            ?.getString(KEY_SERVER_URL)
            ?.trim()
            ?.takeIf { it.isNotEmpty() }
            ?: BuildConfig.ONCALL_DEFAULT_SERVER_URL

        if (serverUrl.isNotEmpty() && repository.getDefaultBaseUrl() != serverUrl) {
            repository.setDefaultBaseUrl(serverUrl)
            Log.i(TAG, "Applied managed OnCall server URL")
        }

        val configUrl = restrictions
            ?.getString(KEY_CONFIG_URL)
            ?.trim()
            ?.takeIf { it.isNotEmpty() }
            ?: BuildConfig.ONCALL_CONFIG_URL
        val enrollmentToken = restrictions
            ?.getString(KEY_ENROLLMENT_TOKEN)
            ?.trim()
            .orEmpty()
        val environment = restrictions
            ?.getString(KEY_ENVIRONMENT)
            ?.trim()
            ?.takeIf { it.isNotEmpty() }
            ?: "prod"

        Log.d(
            TAG,
            "Managed OnCall bootstrap config available: configUrl=$configUrl, environment=$environment, enrollment=${enrollmentToken.isNotEmpty()}",
        )

        // Store the enrollment token as the device_id used for heartbeats and
        // remote config auth. Only written once (on first MDM push or reinstall).
        if (enrollmentToken.isNotEmpty()) {
            val smsPrefs = SmsRelayPreferences(context)
            if (smsPrefs.deviceId != enrollmentToken) {
                smsPrefs.deviceId = enrollmentToken
                smsPrefs.baseUrl = configUrl.substringBeforeLast("/api").trimEnd('/')
                Log.i(TAG, "Stored enrollment token as device_id")
            }
        }
    }
}
