package com.icing.dialer

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyPairGenerator
import java.security.KeyStore

object KeyGeneratorHelper {

    private const val ANDROID_KEYSTORE = "AndroidKeyStore"

    /**
     * Generates an ECDSA P-256 key pair and stores it in the Android Keystore.
     *
     * @param alias Unique identifier for the key pair.
     * @throws Exception if key generation fails.
     */
    fun generateECKeyPair(alias: String) {
        try {
            val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }

            // Check if the key already exists
            if (keyStore.containsAlias(alias)) {
                throw Exception("Key with alias \"$alias\" already exists.")
            }

            val keyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_EC,
                ANDROID_KEYSTORE
            )

            val parameterSpec = KeyGenParameterSpec.Builder(
                alias,
                KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
            )
                .setAlgorithmParameterSpec(java.security.spec.ECGenParameterSpec("secp256r1"))
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512)
                .setUserAuthenticationRequired(false) // Set to true if you require user authentication
                .build()

            keyPairGenerator.initialize(parameterSpec)
            keyPairGenerator.generateKeyPair()
        } catch (e: Exception) {
            throw Exception("Failed to generate EC key pair: ${e.message}", e)
        }
    }
}
