use anyhow::{anyhow, Result};
use reqwest::blocking::Client;
use std::time::Duration;

pub fn post_webhook(url: &str, body: &str, thread_key: Option<&str>) -> Result<()> {
    let mut full_url = url.to_string();
    if let Some(key) = thread_key {
        let sep = if full_url.contains('?') { '&' } else { '?' };
        full_url = format!(
            "{full_url}{sep}threadKey={key}&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
        );
    }

    let client = Client::new();
    let resp = client
        .post(&full_url)
        .header("Content-Type", "application/json; charset=UTF-8")
        .body(body.to_string())
        .timeout(Duration::from_secs(15))
        .send()
        .map_err(|e| anyhow!("webhook POST failed: {e}"))?;

    if !resp.status().is_success() {
        let status = resp.status();
        let text = resp.text().unwrap_or_default();
        return Err(anyhow!("webhook returned HTTP {status}: {text}"));
    }

    Ok(())
}