use hmac::{Hmac, Mac};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

/// HMAC-SHA256 搜索索引。使用 KEK 派生的独立子密钥，与加密密钥分离。
pub fn hmac_hash(key: &[u8; 32], value: &str) -> String {
    let hmac_key = derive_hmac_key(key);
    let mut mac = HmacSha256::new_from_slice(&hmac_key).expect("HMAC key length is valid");
    mac.update(value.as_bytes());
    hex::encode(mac.finalize().into_bytes())
}

/// 从 KEK 派生独立的 HMAC 子密钥，避免密钥复用
fn derive_hmac_key(kek: &[u8; 32]) -> [u8; 32] {
    use sha2::Digest;
    let derived = <Sha256 as Digest>::new()
        .chain_update(b"pii-hmac-index-v1")
        .chain_update(kek)
        .finalize();
    let mut key = [0u8; 32];
    key.copy_from_slice(&derived);
    key
}
