package app.closer.core.notifications

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Handles Android 13+ (API 33) POST_NOTIFICATIONS permission requests.
 *
 * Callers should:
 *  1. Check [isGranted] before asking.
 *  2. If [shouldShowRationale] is true, show an in-app rationale first.
 *  3. Invoke [requestPermission] from an Activity context.
 */
@Singleton
class NotificationPermissionHelper @Inject constructor() {

    val permission: String = Manifest.permission.POST_NOTIFICATIONS

    fun isGranted(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        } else {
            // Pre-Android 13 notifications are granted at install time.
            true
        }
    }

    fun shouldShowRationale(activity: Activity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
        } else {
            false
        }
    }

    fun requestPermission(activity: Activity, requestCode: Int = REQUEST_CODE) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(permission),
                requestCode
            )
        }
    }

    fun onRequestResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ): Boolean {
        if (requestCode != REQUEST_CODE) return false

        val index = permissions.indexOf(permission)
        if (index < 0 || index >= grantResults.size) return false

        return grantResults[index] == PackageManager.PERMISSION_GRANTED
    }

    companion object {
        const val REQUEST_CODE = 9001
    }
}
