package com.icing.dialer

import android.security.keystore.KeyProperties
import java.security.KeyStore
import java.security.Signature
import android.util.Base64
import java.security.PrivateKey

object SignerHelper {

    private const val ANDROID_KEYSTORE = "AndroidKeyStore"

    /**
     * Signs the provided data using the private key associated with the given alias.
     *
     * @param alias The alias of the key pair.
     * @param data The data to sign.
     * @return The signature as a Base64-encoded string.
     * @throws Exception if signing fails.
     */
    fun signData(alias: String, data: ByteArray): String {
        try {
            val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }

            val privateKey = keyStore.getKey(alias, null) as? PrivateKey?: throw Exception("Private key not found for alias \"$alias\".")

            val signature = Signature.getInstance("SHA256withECDSA")
            signature.initSign(privateKey)
            signature.update(data)
            val signedBytes = signature.sign()

            return Base64.encodeToString(signedBytes, Base64.DEFAULT)
        } catch (e: Exception) {
            throw Exception("Failed to sign data: ${e.message}", e)
        }
    }
}
