package expo.modules.rebreakprotection.vpn

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.util.Log

/**
 * Re-establishes ReBreak VPN after device reboot/package replace when the user
 * had protection enabled (`filter_enabled=true`).
 */
class RebreakVpnBootReceiver : BroadcastReceiver() {

  override fun onReceive(context: Context, intent: Intent?) {
    val action = intent?.action ?: return
    if (action !in BOOT_ACTIONS) return

    val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
    val shouldBeOn = prefs.getBoolean(KEY_ENABLED, false)
    if (!shouldBeOn) {
      Log.i(TAG, "boot-restart skipped: filter_enabled=false")
      return
    }

    // Permission can be revoked by OS/user; then we cannot silently restart.
    val consentIntent = try { VpnService.prepare(context) } catch (_: Exception) { null }
    if (consentIntent != null) {
      Log.w(TAG, "boot-restart skipped: VPN consent required")
      prefs.edit().putBoolean(KEY_ENABLED, false).putBoolean(KEY_TAMPER_ARMED, false).apply()
      return
    }

    try {
      val startIntent = Intent(context, RebreakVpnService::class.java)
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(startIntent)
      } else {
        context.startService(startIntent)
      }
      Log.i(TAG, "boot-restart: VPN service started")
    } catch (e: Exception) {
      Log.w(TAG, "boot-restart failed: ${e.message}")
    }
  }

  companion object {
    private const val TAG = "RebreakVpnBoot"
    private const val PREFS = "rebreak_filter_prefs"
    private const val KEY_ENABLED = "filter_enabled"
    private const val KEY_TAMPER_ARMED = "tamper_armed"
    private val BOOT_ACTIONS = setOf(
      Intent.ACTION_BOOT_COMPLETED,
      Intent.ACTION_REBOOT,
      Intent.ACTION_MY_PACKAGE_REPLACED,
      "android.intent.action.QUICKBOOT_POWERON",
      "com.htc.intent.action.QUICKBOOT_POWERON",
    )
  }
}
