1use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
2use serde_json::Value;
3
4use crate::config::{CairnConfig, Credentials};
5use crate::errors::CairnError;
6
7pub struct BackpacClient {
9 inner: reqwest::Client,
10 base_url: String,
11 jwt: Option<String>,
12}
13
14impl BackpacClient {
15 pub fn new(jwt_override: Option<&str>, api_url: Option<&str>) -> Self {
17 let config = CairnConfig::load();
18
19 let base_url = api_url
20 .map(|s| s.to_string())
21 .or(config.api_url.clone())
22 .or_else(|| std::env::var("BACKPAC_API_URL").ok())
23 .unwrap_or_else(|| "https://api.backpac.xyz".to_string());
24
25 let jwt = jwt_override
26 .map(|s| s.to_string())
27 .or_else(|| std::env::var("BACKPAC_JWT").ok())
28 .or_else(|| Credentials::load().map(|c| c.jwt));
29
30 let inner = reqwest::Client::builder()
31 .timeout(std::time::Duration::from_secs(30))
32 .build()
33 .expect("Failed to create HTTP client");
34
35 Self { inner, base_url, jwt }
36 }
37
38 fn auth_headers(&self) -> Result<HeaderMap, CairnError> {
40 let mut headers = HeaderMap::new();
41 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
42
43 if let Some(ref jwt) = self.jwt {
44 let val = format!("Bearer {}", jwt);
45 headers.insert(
46 AUTHORIZATION,
47 HeaderValue::from_str(&val).map_err(|e| CairnError::Auth(e.to_string()))?,
48 );
49 }
50 Ok(headers)
51 }
52
53 pub async fn get(&self, path: &str) -> Result<Value, CairnError> {
55 let url = format!("{}{}", self.base_url, path);
56 let resp = self
57 .inner
58 .get(&url)
59 .headers(self.auth_headers()?)
60 .send()
61 .await?;
62
63 self.handle_response(resp).await
64 }
65
66 pub async fn post(&self, path: &str, body: &Value) -> Result<Value, CairnError> {
68 let url = format!("{}{}", self.base_url, path);
69 let resp = self
70 .inner
71 .post(&url)
72 .headers(self.auth_headers()?)
73 .json(body)
74 .send()
75 .await?;
76
77 self.handle_response(resp).await
78 }
79
80 pub async fn put(&self, path: &str, body: &Value) -> Result<Value, CairnError> {
82 let url = format!("{}{}", self.base_url, path);
83 let resp = self
84 .inner
85 .put(&url)
86 .headers(self.auth_headers()?)
87 .json(body)
88 .send()
89 .await?;
90
91 self.handle_response(resp).await
92 }
93
94 pub async fn rpc_post(
96 &self,
97 body: &Value,
98 poi_id: Option<&str>,
99 confidence: Option<f64>,
100 ) -> Result<Value, CairnError> {
101 let url = format!("{}/", self.base_url);
102 let mut headers = self.auth_headers()?;
103
104 if let Some(poi) = poi_id {
105 headers.insert(
106 "X-Backpac-Poi-Id",
107 HeaderValue::from_str(poi).map_err(|e| CairnError::InvalidInput(e.to_string()))?,
108 );
109 }
110 if let Some(conf) = confidence {
111 headers.insert(
112 "X-Backpac-Confidence",
113 HeaderValue::from_str(&conf.to_string())
114 .map_err(|e| CairnError::InvalidInput(e.to_string()))?,
115 );
116 }
117
118 let resp = self.inner.post(&url).headers(headers).json(body).send().await?;
119 self.handle_response(resp).await
120 }
121
122 async fn handle_response(&self, resp: reqwest::Response) -> Result<Value, CairnError> {
124 let status = resp.status();
125
126 if status.is_success() {
127 let body: Value = resp.json().await?;
128 return Ok(body);
129 }
130
131 let body_text = resp.text().await.unwrap_or_default();
133 let error_msg = serde_json::from_str::<Value>(&body_text)
134 .ok()
135 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
136 .unwrap_or_else(|| body_text.clone());
137
138 match status.as_u16() {
139 400 => Err(CairnError::InvalidInput(error_msg)),
140 401 => {
141 if error_msg.contains("expired") {
142 Err(CairnError::TokenExpired)
143 } else {
144 Err(CairnError::Auth(error_msg))
145 }
146 }
147 402 => {
148 Err(CairnError::InsufficientFunds(
151 "Credits exhausted. x402 auto-payment not yet implemented.".to_string(),
152 ))
153 }
154 403 => Err(CairnError::Auth(error_msg)),
155 404 => Err(CairnError::NotFound(error_msg)),
156 409 => Err(CairnError::Conflict(error_msg)),
157 410 => {
158 if error_msg.contains("expired") {
159 Err(CairnError::IntentExpired(error_msg))
160 } else {
161 Err(CairnError::IntentAborted(error_msg))
162 }
163 }
164 _ => Err(CairnError::General(format!("HTTP {}: {}", status, error_msg))),
165 }
166 }
167}