package com.tt.honeyDue.platform

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import kotlinx.cinterop.ExperimentalForeignApi
import platform.LocalAuthentication.LAContext
import platform.LocalAuthentication.LAPolicyDeviceOwnerAuthenticationWithBiometrics
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

/**
 * iOS implementation of biometric authentication using LocalAuthentication framework (LAContext).
 */
@OptIn(ExperimentalForeignApi::class)
class IOSBiometricAuthPerformer : BiometricAuthPerformer {

    override fun isBiometricAvailable(): Boolean {
        val context = LAContext()
        return context.canEvaluatePolicy(
            LAPolicyDeviceOwnerAuthenticationWithBiometrics,
            error = null
        )
    }

    override fun authenticate(
        title: String,
        subtitle: String,
        onResult: (BiometricResult) -> Unit
    ) {
        if (!isBiometricAvailable()) {
            onResult(BiometricResult.NotAvailable)
            return
        }

        val context = LAContext()
        context.localizedFallbackTitle = ""

        context.evaluatePolicy(
            LAPolicyDeviceOwnerAuthenticationWithBiometrics,
            localizedReason = subtitle
        ) { success, error ->
            MainScope().launch {
                if (success) {
                    onResult(BiometricResult.Success)
                } else {
                    val message = error?.localizedDescription ?: "Authentication failed"
                    onResult(BiometricResult.Failed(message))
                }
            }
        }
    }
}

@Composable
actual fun rememberBiometricAuth(): BiometricAuthPerformer {
    return remember { IOSBiometricAuthPerformer() }
}
