//! Thin HTTP client for the JLCPCB Node backend.
//!
//! Unlike mouser/digikey (which proxy external APIs from Rust), the JLCPCB
//! service is a Node.js HTTP server backed by a local 1.3GB SQLite + FTS5
//! database (from CDFER/jlcpcb-parts-database). This module doesn't
//! reimplement that — it just POSTs JSON actions to the backend and
//! returns the response as-is.

use serde_json::Value;
use std::time::Duration;

pub const DEFAULT_LOCAL: &str = "http://127.0.0.1:8774";
pub const FETCH_TIMEOUT_SECS: u64 = 30;

pub fn resolve_backend(explicit: Option<String>) -> Option<String> {
    if let Some(api) = explicit.filter(|s| !s.is_empty()) {
        return Some(api);
    }
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(2)).build();
    match agent.get(&format!("{}/health", DEFAULT_LOCAL)).call() {
        Ok(_) => Some(DEFAULT_LOCAL.into()),
        Err(ureq::Error::Status(_, _)) => Some(DEFAULT_LOCAL.into()),
        Err(_) => None,
    }
}

pub fn post_action(api: &str, body: Value) -> Result<Value, String> {
    let url = if api.ends_with('/') { api.to_string() } else { format!("{}/", api) };
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(FETCH_TIMEOUT_SECS)).build();
    let res = match agent.post(&url).set("Content-Type", "application/json").send_json(body) {
        Ok(r) => r,
        Err(ureq::Error::Status(_code, r)) => r,
        Err(e) => return Err(format!("JLCPCB backend POST failed: {}", e)),
    };
    res.into_json().map_err(|e| format!("JLCPCB backend JSON parse failed: {}", e))
}

pub fn get_health(api: &str) -> Result<Value, String> {
    let url = if api.ends_with('/') { format!("{}health", api) } else { format!("{}/health", api) };
    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(10)).build();
    let res = match agent.get(&url).call() {
        Ok(r) => r,
        Err(ureq::Error::Status(_code, r)) => r,
        Err(e) => return Err(format!("JLCPCB backend GET /health failed: {}", e)),
    };
    res.into_json().map_err(|e| format!("JLCPCB backend /health JSON parse failed: {}", e))
}