1use reqwest::Client;
2use serde::{Deserialize, Serialize};
3
4#[derive(Serialize)]
5struct ChatRequest {
6 message: String,
7 channel: String,
8 sender: String,
9}
10
11#[derive(Deserialize)]
12struct ChatResponse {
13 response: String,
14}
15
16#[derive(Clone)]
18pub struct BridgeClient {
19 client: Client,
20 base_url: String,
21 url: String,
22 secret: Option<String>,
23}
24
25impl BridgeClient {
26 pub fn new(bridge_url: &str, secret: Option<String>) -> Self {
27 let base = bridge_url.trim_end_matches('/').to_string();
28 Self {
29 client: Client::new(),
30 url: format!("{}/chat", base),
31 base_url: base,
32 secret,
33 }
34 }
35
36 pub async fn dashboard(&self) -> Result<String, String> {
38 let url = format!("{}/api/dashboard", self.base_url);
39 let mut http_req = self.client.get(&url);
40
41 if let Some(secret) = &self.secret {
42 http_req = http_req.header("X-Echo-Secret", secret);
43 }
44
45 let resp = http_req
46 .send()
47 .await
48 .map_err(|e| format!("backend unreachable: {e}"))?;
49
50 if !resp.status().is_success() {
51 return Err(format!("backend returned {}", resp.status()));
52 }
53
54 resp.text()
55 .await
56 .map_err(|e| format!("invalid response: {e}"))
57 }
58
59 pub async fn send(&self, message: &str) -> Result<String, String> {
61 let req = ChatRequest {
62 message: message.to_string(),
63 channel: "web".to_string(),
64 sender: "user".to_string(),
65 };
66
67 let mut http_req = self.client.post(&self.url).json(&req);
68
69 if let Some(secret) = &self.secret {
70 http_req = http_req.header("X-Echo-Secret", secret);
71 }
72
73 let resp = http_req
74 .send()
75 .await
76 .map_err(|e| format!("backend unreachable: {e}"))?;
77
78 if !resp.status().is_success() {
79 return Err(format!("backend returned {}", resp.status()));
80 }
81
82 let body: ChatResponse = resp
83 .json()
84 .await
85 .map_err(|e| format!("invalid response from backend: {e}"))?;
86
87 Ok(body.response)
88 }
89}