use tracing::{info, warn};

/// Signals the local Radicle node to announce updated refs for `rid`.
///
/// Radicle Heartwood exposes an HTTP API at `http://127.0.0.1:8776`. After
/// writing a new audit commit to the Radicle storage repo, we POST to the node
/// sync endpoint so gossip propagates immediately rather than waiting for the
/// node's background scan interval.
///
/// Failure here is non-fatal: the commit is already durable in the local git
/// store and radicled will eventually pick it up via its storage-directory
/// watcher. We log a warning and return Ok(()) so the caller can ack the
/// JetStream message.
pub async fn announce_repo(rid: &str, node_api_url: &str) -> Result<(), crate::error::MirrorError> {
    let url = format!("{node_api_url}/v1/repos/{rid}/sync");

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build()
        .map_err(|e| crate::error::MirrorError::Nats(format!("HTTP client init: {e}")))?;

    match client.post(&url).send().await {
        Ok(resp) if resp.status().is_success() => {
            info!(rid, "Radicle repo sync triggered successfully");
        }
        Ok(resp) => {
            warn!(rid, status = %resp.status(), "Radicle sync returned non-success; node will sync on next scan");
        }
        Err(e) => {
            warn!(rid, error = %e, "Radicle sync request failed (non-fatal; local commit is durable)");
        }
    }

    Ok(())
}
