use bytes::Bytes;
use chrono::Utc;

use crate::{
    error::KeeperError,
    nats_client::KeeperNats,
    types::{AuditEvent, PendingOp},
};

/// Publish an audit event to ops.audit.<workspace> for every signing decision.
/// Called for all decisions (auto_sign, require_manual, hold_pending) so the
/// audit stream has a complete record of what the keeper saw and decided.
pub async fn emit_audit(
    nats: &KeeperNats,
    op: &PendingOp,
    jti: &str,
    issuer_id: &str,
    decision: &str,
) -> Result<(), KeeperError> {
    let event = AuditEvent {
        jti: jti.to_string(),
        workspace: nats.workspace().to_string(),
        op_type: op.op_type.clone(),
        target: op.target.clone(),
        signer_iss: issuer_id.to_string(),
        signed_at: Utc::now().timestamp(),
        decision: decision.to_string(),
    };

    let payload = serde_json::to_vec(&event)?;
    nats.publish_audit(Bytes::from(payload)).await?;
    Ok(())
}
