//
//  BiometricAuthPlugin.swift
//  CapacitorBiometricAuthentication
//
//  2.3.0 SECURITY OVERHAUL — UNVERIFIED-ON-DEVICE.
//  This file was rewritten for the 2.3.0 security release. It MUST be built and
//  tested on real iOS hardware (and Simulator) by the maintainer before publishing.
//  Highlights of this pass (see CHANGELOG / audit IDs IOS-1..IOS-11, BLD-2):
//    - No fabricated signatures: key-gen / signing failures now reject with an
//      honest error instead of returning a placeholder "fallback_sig_*" value.
//    - Secure Enclave signing key is biometric-gated (.privateKeyUsage +
//      .biometryCurrentSet) and software fallback (Simulator / unsupported HW
//      only) is given equivalent access control.
//    - Session token, sign counts, and lockout state are stored in the Keychain
//      (no more UserDefaults for sensitive data); sign count never decreases.
//    - Lockout (failed attempts + end time) survives app relaunch.
//    - biometryType handles .opticID; LAError mapping distinguishes userFallback
//      and passcodeNotSet; error codes are UPPER_CASE to match the JS layer.
//    - All logging is gated behind #if DEBUG and never prints secrets.
//
//  Device verification required before release.
//

import Foundation
import UIKit
import Capacitor
import LocalAuthentication
import Security
import CommonCrypto

@objc(BiometricAuthPlugin)
public class BiometricAuthPlugin: CAPPlugin {
    private let SESSION_TOKEN_KEY = "session_token"
    private let SESSION_EXPIRY_KEY = "session_expiry"
    private let STORED_CREDENTIALS_KEY = "stored_credentials"
    private let KEYCHAIN_SERVICE = "com.aoneahsan.biometricauth"
    private let SIGN_COUNT_KEY = "sign_count_"
    private let LOCKOUT_FAILED_ATTEMPTS_KEY = "lockout_failed_attempts"
    private let LOCKOUT_END_TIME_KEY = "lockout_end_time"

    // UPPER_CASE error codes — kept consistent with the JS error mapping layer
    // (src/adapters/CapacitorAdapter.ts -> mapError codeMap).
    private enum ErrorCode {
        static let userCancelled = "USER_CANCELLED"
        static let userFallback = "USER_FALLBACK"
        static let systemCancelled = "SYSTEM_CANCELLED"
        static let authenticationFailed = "AUTHENTICATION_FAILED"
        static let lockedOut = "LOCKED_OUT"
        static let notAvailable = "NOT_AVAILABLE"
        static let notEnrolled = "NOT_ENROLLED"
        static let passcodeNotSet = "PASSCODE_NOT_SET"
        static let keyGenerationFailed = "KEY_GENERATION_FAILED"
        static let signingFailed = "SIGNING_FAILED"
        static let unknown = "UNKNOWN"
    }

    // Key-protection level used when reporting how the signing key is stored.
    private enum KeyProtection: String {
        case secureEnclave = "secureEnclave"
        case software = "software"
    }

    // Configuration (persisted defaults — never mutated by per-call options).
    private var sessionDuration: TimeInterval = 3600 // 1 hour default
    private var allowDeviceCredential = true
    private var maxAttempts = 3
    private var lockoutDuration: TimeInterval = 30 // 30 seconds

    // MARK: - Debug logging (never prints secrets / credential / signature bytes)

    private func debugLog(_ message: String) {
        #if DEBUG
        // Intentionally only logs high-level, non-sensitive context.
        print("[BiometricAuth] \(message)")
        #endif
    }

    // MARK: - Base64URL utilities for WebAuthn compatibility

    private func base64UrlEncode(_ data: Data) -> String {
        return data.base64EncodedString()
            .replacingOccurrences(of: "+", with: "-")
            .replacingOccurrences(of: "/", with: "_")
            .replacingOccurrences(of: "=", with: "")
    }

    private func base64UrlDecode(_ string: String) -> Data? {
        var base64 = string
            .replacingOccurrences(of: "-", with: "+")
            .replacingOccurrences(of: "_", with: "/")

        // Add padding if needed
        while base64.count % 4 != 0 {
            base64 += "="
        }

        return Data(base64Encoded: base64)
    }

    // MARK: - Keychain helpers (generic password storage for session/sign-count/lockout)

    /// Store (or update) a generic-password keychain item for this service.
    /// Uses `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` so values survive
    /// relaunch but never leave the device and are unavailable before first unlock.
    @discardableResult
    private func keychainSet(account: String, data: Data) -> Bool {
        let baseQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: KEYCHAIN_SERVICE,
            kSecAttrAccount as String: account
        ]

        // Delete any existing item first to avoid duplicate errors.
        SecItemDelete(baseQuery as CFDictionary)

        var addQuery = baseQuery
        addQuery[kSecValueData as String] = data
        addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly

        let status = SecItemAdd(addQuery as CFDictionary, nil)
        if status != errSecSuccess {
            debugLog("keychainSet failed for account=\(account) status=\(status)")
        }
        return status == errSecSuccess
    }

    private func keychainGet(account: String) -> Data? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: KEYCHAIN_SERVICE,
            kSecAttrAccount as String: account,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]

        var item: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &item)
        guard status == errSecSuccess else {
            return nil
        }
        return item as? Data
    }

    @discardableResult
    private func keychainDelete(account: String) -> Bool {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: KEYCHAIN_SERVICE,
            kSecAttrAccount as String: account
        ]
        let status = SecItemDelete(query as CFDictionary)
        return status == errSecSuccess || status == errSecItemNotFound
    }

    private func keychainSetString(account: String, value: String) {
        keychainSet(account: account, data: Data(value.utf8))
    }

    private func keychainGetString(account: String) -> String? {
        guard let data = keychainGet(account: account) else { return nil }
        return String(data: data, encoding: .utf8)
    }

    private func keychainSetInt(account: String, value: Int) {
        keychainSetString(account: account, value: String(value))
    }

    private func keychainGetInt(account: String) -> Int? {
        guard let value = keychainGetString(account: account) else { return nil }
        return Int(value)
    }

    // MARK: - Token / client-data helpers

    private func createEnhancedToken(credentialId: String, type: String, credentialData: [String: Any]? = nil) -> String? {
        var tokenPayload: [String: Any] = [
            "credentialId": credentialId,
            "timestamp": Date().timeIntervalSince1970 * 1000,
            "sessionId": UUID().uuidString,
            "type": type
        ]

        if let credentialData = credentialData {
            tokenPayload["credentialData"] = credentialData
        }

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: tokenPayload)
            return jsonData.base64EncodedString()
        } catch {
            // Do NOT fabricate a token on failure — surface nil so the caller can
            // reject honestly rather than returning a meaningless value.
            debugLog("Failed to create enhanced token")
            return nil
        }
    }

    private func createClientDataJSON(type: String, challenge: String) -> String {
        // Get actual bundle identifier for proper origin
        let bundleId = Bundle.main.bundleIdentifier ?? "unknown"
        let clientData: [String: Any] = [
            "type": type,
            "challenge": Data(challenge.utf8).base64EncodedString(),
            "origin": "ios:bundle-id:\(bundleId)",
            "iosBundleId": bundleId,
            "crossOrigin": false
        ]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: clientData)
            return String(data: jsonData, encoding: .utf8) ?? "{}"
        } catch {
            debugLog("Failed to create client data JSON")
            return "{}"
        }
    }

    /// Get RP ID from options or use bundle identifier
    private func getRpId(from webAuthnOptions: [String: Any]?) -> String {
        if let options = webAuthnOptions {
            if let getOptions = options["get"] as? [String: Any],
               let rpId = getOptions["rpId"] as? String, !rpId.isEmpty {
                return rpId
            }
            if let createOptions = options["create"] as? [String: Any],
               let rp = createOptions["rp"] as? [String: Any],
               let rpId = rp["id"] as? String, !rpId.isEmpty {
                return rpId
            }
        }
        return Bundle.main.bundleIdentifier ?? "unknown"
    }

    /// Get and increment sign count for replay protection.
    /// Stored in the Keychain (not UserDefaults) and never allowed to decrease.
    private func getAndIncrementSignCount(for credentialId: String) -> Int {
        let account = SIGN_COUNT_KEY + credentialId
        let current = keychainGetInt(account: account) ?? 0
        let next = current &+ 1
        // Monotonic guard: only persist when the value actually increases.
        if next > current {
            keychainSetInt(account: account, value: next)
        }
        return current
    }

    /// Generate WebAuthn-compliant authenticatorData
    private func generateAuthenticatorData(rpId: String, signCount: Int, userPresent: Bool, userVerified: Bool) -> Data {
        // Calculate rpIdHash (SHA-256 of the RP ID)
        guard let rpIdData = rpId.data(using: .utf8) else {
            return Data()
        }
        var rpIdHash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        rpIdData.withUnsafeBytes { bytes in
            _ = CC_SHA256(bytes.baseAddress, CC_LONG(rpIdData.count), &rpIdHash)
        }

        // Build flags byte
        var flags: UInt8 = 0
        if userPresent { flags |= 0x01 }
        if userVerified { flags |= 0x04 }

        // Sign count (4 bytes, big-endian)
        let signCountBytes: [UInt8] = [
            UInt8((signCount >> 24) & 0xFF),
            UInt8((signCount >> 16) & 0xFF),
            UInt8((signCount >> 8) & 0xFF),
            UInt8(signCount & 0xFF)
        ]

        // Combine: rpIdHash (32) + flags (1) + signCount (4) = 37 bytes
        var authenticatorData = Data(rpIdHash)
        authenticatorData.append(flags)
        authenticatorData.append(contentsOf: signCountBytes)

        return authenticatorData
    }

    // MARK: - Signing keys

    /// Result of a signing attempt — an honest success/failure, never fabricated.
    private enum SignatureResult {
        case success(String)
        case failure(code: String, message: String)
    }

    /// Sign data with the Keychain-stored key. Returns a real signature on success
    /// or an explicit failure (NO placeholder/fabricated signature is ever returned).
    private func generateRealSignature(keyAlias: String, dataToSign: Data) -> SignatureResult {
        let key: SecKey
        if let existingKey = getPrivateKey(alias: keyAlias) {
            key = existingKey
        } else {
            switch generateKeyPair(alias: keyAlias) {
            case .success(let newKey, _):
                key = newKey
            case .failure(let code, let message):
                return .failure(code: code, message: message)
            }
        }

        var error: Unmanaged<CFError>?
        guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, dataToSign as CFData, &error) else {
            // Honest failure — do not return a fabricated signature.
            debugLog("SecKeyCreateSignature failed")
            error?.release()
            return .failure(code: ErrorCode.signingFailed, message: "Failed to sign authentication data")
        }

        return .success(base64UrlEncode(signature as Data))
    }

    /// Result of a key-pair generation attempt.
    private enum KeyGenResult {
        case success(SecKey, KeyProtection)
        case failure(code: String, message: String)
    }

    /// Determine whether the build is running on the iOS Simulator, where the
    /// Secure Enclave is not available and a software key is the only option.
    private var isSimulator: Bool {
        #if targetEnvironment(simulator)
        return true
        #else
        return false
        #endif
    }

    /// Generate a biometric-gated key pair for signatures.
    ///
    /// Primary path: Secure Enclave key with access control
    /// `[.privateKeyUsage, .biometryCurrentSet]` — the private key requires a fresh
    /// biometric match to produce a signature and is invalidated when the enrolled
    /// biometric set changes.
    ///
    /// Fallback path (Simulator OR `errSecUnimplemented` only — never a silent
    /// downgrade on capable hardware): a software key that is ALSO protected by an
    /// equivalent biometric-gated access control.
    private func generateKeyPair(alias: String) -> KeyGenResult {
        guard let tag = "\(KEYCHAIN_SERVICE).\(alias)".data(using: .utf8) else {
            return .failure(code: ErrorCode.keyGenerationFailed, message: "Invalid key alias")
        }

        // Delete any existing key with this alias.
        let deleteQuery: [String: Any] = [
            kSecClass as String: kSecClassKey,
            kSecAttrApplicationTag as String: tag
        ]
        SecItemDelete(deleteQuery as CFDictionary)

        // Biometric-gated access control: fresh biometric match required to sign,
        // invalidated when the enrolled set changes.
        var acError: Unmanaged<CFError>?
        guard let access = SecAccessControlCreateWithFlags(
            kCFAllocatorDefault,
            kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
            [.privateKeyUsage, .biometryCurrentSet],
            &acError
        ) else {
            debugLog("Failed to create access control")
            acError?.release()
            return .failure(code: ErrorCode.keyGenerationFailed, message: "Failed to create key access control")
        }

        // Secure Enclave path (real hardware).
        if !isSimulator {
            let attributes: [String: Any] = [
                kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
                kSecAttrKeySizeInBits as String: 256,
                kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
                kSecPrivateKeyAttrs as String: [
                    kSecAttrIsPermanent as String: true,
                    kSecAttrApplicationTag as String: tag,
                    kSecAttrAccessControl as String: access
                ]
            ]

            var seError: Unmanaged<CFError>?
            if let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &seError) {
                return .success(privateKey, .secureEnclave)
            }

            // Only fall back when the Secure Enclave is genuinely unsupported
            // (errSecUnimplemented). Any other failure is surfaced honestly so we
            // never silently downgrade key protection on capable hardware.
            let seCode = (seError?.takeRetainedValue()).map { CFErrorGetCode($0) } ?? Int(errSecParam)
            if seCode != Int(errSecUnimplemented) {
                debugLog("Secure Enclave key generation failed (code \(seCode)); not downgrading")
                return .failure(code: ErrorCode.keyGenerationFailed, message: "Secure Enclave key generation failed")
            }
            debugLog("Secure Enclave unsupported (errSecUnimplemented); using software key fallback")
        }

        // Software-key fallback (Simulator / SE unsupported) — still given an
        // equivalent biometric-gated access control so it is never unprotected.
        let softwareAttributes: [String: Any] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
            kSecAttrKeySizeInBits as String: 256,
            kSecPrivateKeyAttrs as String: [
                kSecAttrIsPermanent as String: true,
                kSecAttrApplicationTag as String: tag,
                kSecAttrAccessControl as String: access
            ]
        ]

        var swError: Unmanaged<CFError>?
        if let softwareKey = SecKeyCreateRandomKey(softwareAttributes as CFDictionary, &swError) {
            return .success(softwareKey, .software)
        }

        debugLog("Software key generation failed")
        swError?.release()
        return .failure(code: ErrorCode.keyGenerationFailed, message: "Failed to generate signing key")
    }

    /// Get existing private key from Keychain
    private func getPrivateKey(alias: String) -> SecKey? {
        guard let tag = "\(KEYCHAIN_SERVICE).\(alias)".data(using: .utf8) else {
            return nil
        }
        let query: [String: Any] = [
            kSecClass as String: kSecClassKey,
            kSecAttrApplicationTag as String: tag,
            kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
            kSecReturnRef as String: true
        ]

        var item: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &item)

        guard status == errSecSuccess, let key = item else {
            return nil
        }

        // CFTypeRef holding a SecKey — cast safely without force-unwrap.
        return (key as! SecKey)
    }

    /// Get public key as base64
    private func getPublicKeyBase64(alias: String) -> String? {
        guard let privateKey = getPrivateKey(alias: alias),
              let publicKey = SecKeyCopyPublicKey(privateKey) else {
            return nil
        }

        var error: Unmanaged<CFError>?
        guard let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, &error) else {
            error?.release()
            return nil
        }

        return (publicKeyData as Data).base64EncodedString()
    }

    /// Delete all signing keys (kSecClassKey) created by this plugin.
    @discardableResult
    private func deleteAllSigningKeys() -> Bool {
        // Keys are tagged with "<KEYCHAIN_SERVICE>.<alias>". There is no service
        // attribute on key-class items, so delete by class. We scope deletion to
        // this plugin's items by matching the application-tag prefix where possible;
        // SecItemDelete cannot prefix-match, so we enumerate and delete by tag.
        let query: [String: Any] = [
            kSecClass as String: kSecClassKey,
            kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
            kSecMatchLimit as String: kSecMatchLimitAll,
            kSecReturnAttributes as String: true
        ]

        var items: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &items)
        guard status == errSecSuccess, let attributesList = items as? [[String: Any]] else {
            // Nothing to delete (or not found) is success for our purposes.
            return status == errSecItemNotFound || status == errSecSuccess
        }

        guard let servicePrefixData = "\(KEYCHAIN_SERVICE).".data(using: .utf8) else {
            return false
        }

        var allDeleted = true
        for attributes in attributesList {
            guard let tagData = attributes[kSecAttrApplicationTag as String] as? Data else {
                continue
            }
            // Only delete keys belonging to this plugin (tag begins with our prefix).
            if tagData.starts(with: servicePrefixData) {
                let deleteQuery: [String: Any] = [
                    kSecClass as String: kSecClassKey,
                    kSecAttrApplicationTag as String: tagData
                ]
                let delStatus = SecItemDelete(deleteQuery as CFDictionary)
                if delStatus != errSecSuccess && delStatus != errSecItemNotFound {
                    allDeleted = false
                }
            }
        }
        return allDeleted
    }

    /// Generate attestation object
    private func generateAttestationObject(authenticatorData: Data) -> Data {
        // Create a JSON-based attestation for "none" format
        let attestation: [String: Any] = [
            "fmt": "none",
            "attStmt": [:],
            "authData": authenticatorData.base64EncodedString()
        ]

        do {
            return try JSONSerialization.data(withJSONObject: attestation)
        } catch {
            debugLog("Failed to generate attestation object")
            return Data()
        }
    }

    // MARK: - Lockout (persisted to Keychain so the throttle survives relaunch)

    private func loadLockoutState() -> (failedAttempts: Int, lockoutEndTime: Date?) {
        let attempts = keychainGetInt(account: LOCKOUT_FAILED_ATTEMPTS_KEY) ?? 0
        var endTime: Date?
        if let raw = keychainGetString(account: LOCKOUT_END_TIME_KEY),
           let interval = TimeInterval(raw) {
            endTime = Date(timeIntervalSince1970: interval)
        }
        return (attempts, endTime)
    }

    private func persistLockoutState(failedAttempts: Int, lockoutEndTime: Date?) {
        keychainSetInt(account: LOCKOUT_FAILED_ATTEMPTS_KEY, value: failedAttempts)
        if let endTime = lockoutEndTime {
            keychainSetString(account: LOCKOUT_END_TIME_KEY, value: String(endTime.timeIntervalSince1970))
        } else {
            keychainDelete(account: LOCKOUT_END_TIME_KEY)
        }
    }

    /// Returns remaining lockout seconds if currently locked out, otherwise nil.
    private func remainingLockoutSeconds() -> Int? {
        let state = loadLockoutState()
        if let endTime = state.lockoutEndTime {
            if Date() < endTime {
                return max(0, Int(endTime.timeIntervalSince(Date())))
            }
            // Lockout window expired — clear it.
            persistLockoutState(failedAttempts: 0, lockoutEndTime: nil)
        }
        return nil
    }

    /// Handle a failed attempt; trips the lockout when maxAttempts is reached.
    private func handleFailedAttempt() {
        var state = loadLockoutState()
        state.failedAttempts += 1
        if state.failedAttempts >= maxAttempts {
            persistLockoutState(failedAttempts: 0, lockoutEndTime: Date().addingTimeInterval(lockoutDuration))
        } else {
            persistLockoutState(failedAttempts: state.failedAttempts, lockoutEndTime: nil)
        }
    }

    /// Reset failed attempts on success.
    private func resetFailedAttempts() {
        persistLockoutState(failedAttempts: 0, lockoutEndTime: nil)
    }

    private func generateDeviceFingerprint() -> String {
        var fingerprintComponents: [String] = []

        // Device model
        var systemInfo = utsname()
        uname(&systemInfo)
        let deviceModel = withUnsafeBytes(of: &systemInfo.machine) { rawBuffer -> String in
            let data = Data(rawBuffer)
            return String(data: data, encoding: .ascii)?
                .trimmingCharacters(in: .controlCharacters) ?? "unknown"
        }
        fingerprintComponents.append(deviceModel)

        // Screen resolution
        let screenSize = UIScreen.main.bounds
        let screenScale = UIScreen.main.scale
        let screenInfo = "\(Int(screenSize.width * screenScale))x\(Int(screenSize.height * screenScale))"
        fingerprintComponents.append(screenInfo)

        // Language/Locale
        let locale = Locale.current.identifier
        fingerprintComponents.append(locale)

        // Timezone
        let timezone = TimeZone.current.identifier
        fingerprintComponents.append(timezone)

        // iOS version
        let iosVersion = UIDevice.current.systemVersion
        fingerprintComponents.append(iosVersion)

        let fingerprint = fingerprintComponents.joined(separator: "|")
        let fingerprintData = fingerprint.data(using: .utf8) ?? Data()
        let base64Fingerprint = fingerprintData.base64EncodedString()

        // Return first 32 characters
        return String(base64Fingerprint.prefix(32))
    }

    // MARK: - Per-call option resolution (IOS-9)

    /// Whether device credential (passcode) fallback is allowed for THIS call.
    /// Honors per-call `disableDeviceCredential` / `disableFallback` / `biometricOnly`
    /// without mutating the persisted `allowDeviceCredential` configuration.
    private func resolveAllowDeviceCredential(_ call: CAPPluginCall) -> Bool {
        if let biometricOnly = call.getBool("biometricOnly"), biometricOnly {
            return false
        }
        if let disable = call.getBool("disableDeviceCredential"), disable {
            return false
        }
        if let disableFallback = call.getBool("disableFallback"), disableFallback {
            return false
        }
        return allowDeviceCredential
    }

    /// Resolve the cancel-button title from any of the accepted per-call keys.
    private func resolveCancelTitle(_ call: CAPPluginCall) -> String {
        return call.getString("cancelButtonTitle")
            ?? call.getString("cancelTitle")
            ?? call.getString("localizedCancelTitle")
            ?? "Cancel"
    }

    /// Resolve the fallback-button title from any of the accepted per-call keys.
    private func resolveFallbackTitle(_ call: CAPPluginCall) -> String? {
        return call.getString("localizedFallbackTitle")
            ?? call.getString("fallbackButtonTitle")
            ?? call.getString("fallbackTitle")
    }

    // MARK: - Public API

    @objc func isAvailable(_ call: CAPPluginCall) {
        let context = LAContext()
        var error: NSError?

        let allowDeviceCredentialForCall = resolveAllowDeviceCredential(call)
        let policy: LAPolicy = allowDeviceCredentialForCall ? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics
        let canAuthenticate = context.canEvaluatePolicy(policy, error: &error)

        // Include BOTH `available` (legacy) and `isAvailable` (the key the JS
        // adapter reads) to keep the contract intact.
        var result: [String: Any] = [
            "available": canAuthenticate,
            "isAvailable": canAuthenticate
        ]
        if !canAuthenticate, let error = error {
            var reason = ""
            switch error.code {
            case LAError.biometryNotAvailable.rawValue:
                reason = "hardwareUnavailable"
            case LAError.biometryNotEnrolled.rawValue:
                reason = "noEnrolledBiometrics"
            case LAError.biometryLockout.rawValue:
                reason = "lockedOut"
            case LAError.passcodeNotSet.rawValue:
                // A missing device passcode is "not enrolled", NOT "no hardware".
                reason = "noEnrolledBiometrics"
            default:
                reason = "notSupported"
            }
            result["reason"] = reason
            result["errorMessage"] = error.localizedDescription
        }

        call.resolve(result)
    }

    @objc func getSupportedBiometrics(_ call: CAPPluginCall) {
        let context = LAContext()
        var error: NSError?
        var biometrics: [String] = []

        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            switch context.biometryType {
            case .touchID:
                biometrics.append("touchId")
            case .faceID:
                biometrics.append("faceId")
            default:
                // .opticID (iOS 17+/visionOS) is handled below when available.
                if #available(iOS 17.0, *), context.biometryType == .opticID {
                    biometrics.append("opticId")
                }
                // .none and any future @unknown cases contribute nothing.
            }
        }

        let allowDeviceCredentialForCall = resolveAllowDeviceCredential(call)
        if allowDeviceCredentialForCall && context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
            biometrics.append("passcode")
        }

        // Include BOTH `biometrics` (legacy) and `biometryTypes` (the key the JS
        // adapter reads) to keep the contract intact.
        call.resolve([
            "biometrics": biometrics,
            "biometryTypes": biometrics
        ])
    }

    @objc func authenticate(_ call: CAPPluginCall) {
        // Check for lockout (persisted — survives relaunch).
        if let remaining = remainingLockoutSeconds() {
            call.resolve([
                "success": false,
                "error": [
                    "code": ErrorCode.lockedOut,
                    "message": "Too many failed attempts. Please try again in \(remaining) seconds."
                ]
            ])
            return
        }

        let allowDeviceCredentialForCall = resolveAllowDeviceCredential(call)

        let context = LAContext()
        context.localizedCancelTitle = resolveCancelTitle(call)

        // With `.deviceOwnerAuthentication` the system fallback IS the device
        // passcode, so a custom fallback title only applies when device credential
        // is disabled (biometric-only) and LocalAuthentication shows our fallback.
        if !allowDeviceCredentialForCall, let fallbackTitle = resolveFallbackTitle(call) {
            context.localizedFallbackTitle = fallbackTitle
        }

        let reason = call.getString("description")
            ?? call.getString("subtitle")
            ?? call.getString("title")
            ?? call.getString("reason")
            ?? "Authenticate to continue"

        // Extract WebAuthn options
        let webAuthnOptions = call.getObject("webAuthnOptions")
        var webAuthnChallenge: String?
        if let options = webAuthnOptions,
           let getOptions = options["get"] as? [String: Any],
           let challenge = getOptions["challenge"] as? String {
            webAuthnChallenge = challenge
        }

        let policy: LAPolicy = allowDeviceCredentialForCall ? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics

        context.evaluatePolicy(policy, localizedReason: reason) { success, error in
            DispatchQueue.main.async {
                if success {
                    // Extract stored credential information from WebAuthn options if available
                    var credentialId = "mobile_" + UUID().uuidString.replacingOccurrences(of: "-", with: "")
                    var credentialRawId: String?
                    var userId: String?

                    if let options = webAuthnOptions,
                       let getOptions = options["get"] as? [String: Any] {
                        if let storedCredentialId = getOptions["storedCredentialId"] as? String, !storedCredentialId.isEmpty {
                            credentialId = storedCredentialId
                        }
                        if let storedCredentialRawId = getOptions["storedCredentialRawId"] as? String, !storedCredentialRawId.isEmpty {
                            credentialRawId = storedCredentialRawId
                        }
                        if let storedUserId = getOptions["storedUserId"] as? String, !storedUserId.isEmpty {
                            userId = storedUserId
                        }
                    }

                    let sessionId = UUID().uuidString

                    // Get RP ID and generate sign count
                    let rpId = self.getRpId(from: webAuthnOptions)
                    let signCount = self.getAndIncrementSignCount(for: credentialId)

                    // Generate proper authenticatorData
                    let authenticatorData = self.generateAuthenticatorData(rpId: rpId, signCount: signCount, userPresent: true, userVerified: true)

                    // Use the WebAuthn challenge if provided, otherwise fallback to timestamp
                    let challengeToUse = webAuthnChallenge ?? "mobile_auth_\(Int(Date().timeIntervalSince1970 * 1000))"
                    let clientDataJSON = self.createClientDataJSON(type: "webauthn.get", challenge: challengeToUse)

                    // Generate REAL signature: sign(authenticatorData || SHA-256(clientDataJSON)).
                    // Any failure here is reported honestly (no fabricated signature).
                    guard let clientDataData = clientDataJSON.data(using: .utf8) else {
                        self.handleFailedAttempt()
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": ErrorCode.signingFailed,
                                "message": "Failed to build client data for signing"
                            ]
                        ])
                        return
                    }

                    var clientDataHash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
                    clientDataData.withUnsafeBytes { bytes in
                        _ = CC_SHA256(bytes.baseAddress, CC_LONG(clientDataData.count), &clientDataHash)
                    }

                    var dataToSign = authenticatorData
                    dataToSign.append(contentsOf: clientDataHash)

                    let keyAlias = "auth_key_\(credentialId)"
                    let signatureString: String
                    switch self.generateRealSignature(keyAlias: keyAlias, dataToSign: dataToSign) {
                    case .success(let sig):
                        signatureString = sig
                    case .failure(let code, let message):
                        // Honest failure — do NOT resolve success with a fake signature.
                        self.handleFailedAttempt()
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": code,
                                "message": message
                            ]
                        ])
                        return
                    }

                    // Only reset the lockout counter once we have a genuine signature.
                    self.resetFailedAttempts()

                    // Create enhanced credential data for backend verification
                    let credentialData: [String: Any] = [
                        "id": credentialId,
                        "rawId": credentialRawId ?? self.base64UrlEncode(credentialId.data(using: .utf8) ?? Data()),
                        "response": [
                            "authenticatorData": self.base64UrlEncode(authenticatorData),
                            "clientDataJSON": self.base64UrlEncode(clientDataJSON.data(using: .utf8) ?? Data()),
                            "signature": signatureString,
                            "userHandle": userId != nil ? self.base64UrlEncode(userId!.data(using: .utf8) ?? Data()) : ""
                        ],
                        "type": "public-key",
                        "clientExtensionResults": "{}",
                        "authenticatorAttachment": "platform",
                        "deviceFingerprint": self.generateDeviceFingerprint()
                    ]

                    // Create enhanced token with credential data
                    guard let token = self.createEnhancedToken(credentialId: credentialId, type: "authentication", credentialData: credentialData) else {
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": ErrorCode.unknown,
                                "message": "Failed to create session token"
                            ]
                        ])
                        return
                    }

                    // Store session token + expiry in the Keychain (not UserDefaults).
                    self.keychainSetString(account: self.SESSION_TOKEN_KEY, value: token)
                    self.keychainSetString(
                        account: self.SESSION_EXPIRY_KEY,
                        value: String(Date().addingTimeInterval(self.sessionDuration).timeIntervalSince1970)
                    )

                    call.resolve([
                        "success": true,
                        "sessionId": sessionId,
                        "token": token
                    ])
                } else {
                    self.handleFailedAttempt()
                    let mapped = self.mapLAError(error, defaultMessage: "Authentication failed")
                    call.resolve([
                        "success": false,
                        "error": [
                            "code": mapped.code,
                            "message": mapped.message
                        ]
                    ])
                }
            }
        }
    }

    @objc func register(_ call: CAPPluginCall) {
        // Check for lockout (persisted — survives relaunch).
        if let remaining = remainingLockoutSeconds() {
            call.resolve([
                "success": false,
                "error": [
                    "code": ErrorCode.lockedOut,
                    "message": "Too many failed attempts. Please try again in \(remaining) seconds."
                ]
            ])
            return
        }

        let allowDeviceCredentialForCall = resolveAllowDeviceCredential(call)

        let context = LAContext()
        context.localizedCancelTitle = resolveCancelTitle(call)

        if !allowDeviceCredentialForCall, let fallbackTitle = resolveFallbackTitle(call) {
            context.localizedFallbackTitle = fallbackTitle
        }

        let reason = call.getString("description")
            ?? call.getString("subtitle")
            ?? call.getString("title")
            ?? call.getString("reason")
            ?? "Register biometric authentication"

        // Extract WebAuthn options
        let webAuthnOptions = call.getObject("webAuthnOptions")

        let policy: LAPolicy = allowDeviceCredentialForCall ? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics

        context.evaluatePolicy(policy, localizedReason: reason) { success, error in
            DispatchQueue.main.async {
                if success {
                    // Generate credential data for mobile registration
                    let credentialId = "mobile_" + UUID().uuidString.replacingOccurrences(of: "-", with: "")
                    let sessionId = UUID().uuidString

                    // Get RP ID and generate sign count
                    let rpId = self.getRpId(from: webAuthnOptions)
                    let signCount = self.getAndIncrementSignCount(for: credentialId)

                    // Generate proper authenticatorData
                    let authenticatorData = self.generateAuthenticatorData(rpId: rpId, signCount: signCount, userPresent: true, userVerified: true)

                    // Generate the biometric-gated key pair for this credential.
                    // If key generation fails, registration MUST fail honestly —
                    // a credential with no usable key is worse than no credential.
                    let keyAlias = "auth_key_\(credentialId)"
                    switch self.generateKeyPair(alias: keyAlias) {
                    case .success(_, let protection):
                        self.debugLog("Registration key created with protection: \(protection.rawValue)")
                    case .failure(let code, let message):
                        self.handleFailedAttempt()
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": code,
                                "message": message
                            ]
                        ])
                        return
                    }

                    guard let publicKeyBase64 = self.getPublicKeyBase64(alias: keyAlias) else {
                        self.handleFailedAttempt()
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": ErrorCode.keyGenerationFailed,
                                "message": "Failed to export public key"
                            ]
                        ])
                        return
                    }

                    self.resetFailedAttempts()

                    // Generate proper attestation object
                    let attestationObject = self.generateAttestationObject(authenticatorData: authenticatorData)

                    // Extract challenge from webAuthnOptions if available
                    var challenge = "mobile_registration_\(Int(Date().timeIntervalSince1970 * 1000))"
                    if let options = webAuthnOptions,
                       let createOptions = options["create"] as? [String: Any],
                       let providedChallenge = createOptions["challenge"] as? String, !providedChallenge.isEmpty {
                        challenge = providedChallenge
                    }

                    // Create enhanced credential data for backend verification
                    let responseData: [String: Any] = [
                        "attestationObject": self.base64UrlEncode(attestationObject),
                        "clientDataJSON": self.base64UrlEncode(self.createClientDataJSON(type: "webauthn.create", challenge: challenge).data(using: .utf8) ?? Data()),
                        "transports": ["internal"],
                        "publicKey": publicKeyBase64
                    ]

                    let credentialData: [String: Any] = [
                        "id": credentialId,
                        "rawId": self.base64UrlEncode(credentialId.data(using: .utf8) ?? Data()),
                        "response": responseData,
                        "type": "public-key",
                        "clientExtensionResults": "{}",
                        "authenticatorAttachment": "platform",
                        "deviceFingerprint": self.generateDeviceFingerprint()
                    ]

                    // Create enhanced token with credential data
                    guard let token = self.createEnhancedToken(credentialId: credentialId, type: "registration", credentialData: credentialData) else {
                        call.resolve([
                            "success": false,
                            "error": [
                                "code": ErrorCode.unknown,
                                "message": "Failed to create session token"
                            ]
                        ])
                        return
                    }

                    // Store session token + expiry in the Keychain (not UserDefaults).
                    self.keychainSetString(account: self.SESSION_TOKEN_KEY, value: token)
                    self.keychainSetString(
                        account: self.SESSION_EXPIRY_KEY,
                        value: String(Date().addingTimeInterval(self.sessionDuration).timeIntervalSince1970)
                    )

                    call.resolve([
                        "success": true,
                        "sessionId": sessionId,
                        "token": token
                    ])
                } else {
                    self.handleFailedAttempt()
                    let mapped = self.mapLAError(error, defaultMessage: "Registration failed")
                    call.resolve([
                        "success": false,
                        "error": [
                            "code": mapped.code,
                            "message": mapped.message
                        ]
                    ])
                }
            }
        }
    }

    @objc func deleteCredentials(_ call: CAPPluginCall) {
        // Clear session / credential generic-password items from the Keychain.
        keychainDelete(account: SESSION_TOKEN_KEY)
        keychainDelete(account: SESSION_EXPIRY_KEY)
        keychainDelete(account: STORED_CREDENTIALS_KEY)
        keychainDelete(account: LOCKOUT_FAILED_ATTEMPTS_KEY)
        keychainDelete(account: LOCKOUT_END_TIME_KEY)

        // Remove ALL generic-password items for this service (covers sign counts,
        // which are stored as "<SIGN_COUNT_KEY><credentialId>" accounts).
        let genericQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: KEYCHAIN_SERVICE
        ]
        let genericStatus = SecItemDelete(genericQuery as CFDictionary)

        // Delete the actual signing keys (kSecClassKey) — previously leaked.
        let keysDeleted = deleteAllSigningKeys()

        let genericOk = (genericStatus == errSecSuccess || genericStatus == errSecItemNotFound)
        if genericOk && keysDeleted {
            call.resolve()
        } else {
            call.reject("Failed to delete credentials")
        }
    }

    /// End the current session WITHOUT destroying enrolled credentials/keys.
    @objc func logout(_ call: CAPPluginCall) {
        keychainDelete(account: SESSION_TOKEN_KEY)
        keychainDelete(account: SESSION_EXPIRY_KEY)
        call.resolve()
    }

    @objc func configure(_ call: CAPPluginCall) {
        if let config = call.getObject("config") {
            if let duration = config["sessionDuration"] as? Double {
                sessionDuration = duration
            }

            if let fallbackMethods = config["fallbackMethods"] as? [String] {
                // Check if any device credential methods are allowed
                allowDeviceCredential = fallbackMethods.contains { method in
                    ["passcode", "pattern", "pin"].contains(method)
                }
            }

            if let attempts = config["maxAttempts"] as? Int {
                maxAttempts = attempts
            }

            if let lockout = config["lockoutDuration"] as? Double {
                lockoutDuration = lockout
            }
        }

        call.resolve()
    }

    // MARK: - LAError mapping (UPPER_CASE codes to match the JS layer)

    private func mapLAError(_ error: Error?, defaultMessage: String) -> (code: String, message: String) {
        guard let nsError = error as NSError? else {
            return (ErrorCode.unknown, defaultMessage)
        }

        switch nsError.code {
        case LAError.userCancel.rawValue:
            return (ErrorCode.userCancelled, "User cancelled authentication")
        case LAError.userFallback.rawValue:
            // Distinct from cancellation: the user explicitly chose the fallback.
            return (ErrorCode.userFallback, "User chose fallback")
        case LAError.systemCancel.rawValue:
            return (ErrorCode.systemCancelled, "System cancelled authentication")
        case LAError.authenticationFailed.rawValue:
            return (ErrorCode.authenticationFailed, "Authentication failed")
        case LAError.biometryLockout.rawValue:
            return (ErrorCode.lockedOut, "Biometry is locked out")
        case LAError.biometryNotAvailable.rawValue:
            return (ErrorCode.notAvailable, "Biometry is not available")
        case LAError.biometryNotEnrolled.rawValue:
            return (ErrorCode.notEnrolled, "No biometric data enrolled")
        case LAError.passcodeNotSet.rawValue:
            // A missing device passcode is its own reason, not "no hardware".
            return (ErrorCode.passcodeNotSet, "Device passcode is not set")
        default:
            return (ErrorCode.unknown, nsError.localizedDescription)
        }
    }
}
