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

use crate::standards::websub::WebSubError;

pub fn sign(secret: &str, body: &[u8]) -> Result<String, WebSubError> {
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
        .map_err(|err| WebSubError::Http(err.to_string()))?;
    mac.update(body);
    let result = mac.finalize();
    Ok(format!("sha256={}", hex::encode(result.into_bytes())))
}

pub fn verify(secret: &str, body: &[u8], signature: &str) -> Result<bool, WebSubError> {
    let signature = signature.trim();
    let signature = signature.strip_prefix("sha256=").unwrap_or(signature);
    let expected = hex::decode(signature).map_err(|err| WebSubError::Http(err.to_string()))?;

    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
        .map_err(|err| WebSubError::Http(err.to_string()))?;
    mac.update(body);
    Ok(mac.verify_slice(&expected).is_ok())
}
