uptrakit-openapi-client 0.0.4

Typed HTTP client for the Uptrakit web API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
#[cfg(feature = "mock")]
pub mod mock;

pub(crate) mod paths;

pub mod access_catalog;
pub mod access_grants;
pub mod api_tokens;
pub mod audit_logs;
pub mod auth;
pub mod autodiscovery;
pub mod batch_progress_stream;
pub mod discovery_allowlist;
pub mod enrollment_tokens;
pub mod error;
pub mod events_stream;
pub mod health;
pub mod host_tags;
pub mod hosts;
pub mod notifications;
pub mod oauth_clients;
pub mod oauth_consents;
pub mod oidc_auth;
pub mod oidc_providers;
pub mod pki;
pub mod plugin_configs;
pub mod plugin_type_settings;
pub mod roles;
pub mod scheduler;
pub mod services;
pub mod settings;
pub mod settings_nats;
pub mod settings_provider_github;
pub mod software_items;
pub mod sse;
pub mod surfaces;
pub mod system_alerts;
pub mod system_enrollment_tokens;
pub mod system_services;
pub mod update_batches;
pub mod update_history;
pub mod update_output_stream;
pub mod users;

pub use error::{ClientError, Result};

pub use uptrakit_shared_types::DeviceAuthStatus;
pub use uptrakit_web_api_types as types;

pub(crate) mod types_impl {
    pub(crate) use uptrakit_web_api_types::*;
}

#[cfg(test)]
pub(crate) mod shared_types_impl {
    pub(crate) use uptrakit_shared_types::*;
}

/// Re-export `Uuid` so that downstream crates can use the exact same type
/// without adding a direct `uuid` dependency.
pub use uuid::Uuid;

/// Re-export `reqwest::Error` so that downstream crates (e.g. the CLI)
/// do not need a direct dependency on `reqwest`.
pub use reqwest::Error as ReqwestError;

/// Re-export `reqwest::StatusCode` so that downstream crates (e.g. the CLI)
/// do not need a direct dependency on `reqwest` for HTTP status handling.
pub use reqwest::StatusCode;

use rootcause::prelude::*;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::time::Duration;

/// Serialize a `StatusCode` as its numeric `u16` value for JSON wire compatibility.
fn serialize_status_code<S: serde::Serializer>(
    status: &reqwest::StatusCode,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    serializer.serialize_u16(status.as_u16())
}

/// Response from a raw (untyped) API request.
#[derive(Debug, Serialize)]
pub struct RawResponse {
    #[serde(serialize_with = "serialize_status_code")]
    pub status: reqwest::StatusCode,
    pub body: serde_json::Value,
}

/// Configuration for automatic retry on transient failures.
///
/// Apply with [`UptrakitClient::with_retry`]. By default the client fails fast
/// with no retries; call `with_retry(RetryConfig::default())` to enable.
///
/// Retries are applied to:
/// - **HTTP 429 Too Many Requests**: respects the `Retry-After` header if
///   present (numeric seconds only); falls back to `initial_delay`.
/// - **HTTP 5xx Server Error**: exponential backoff starting at `initial_delay`,
///   doubling on each attempt, capped at `max_delay`.
///
/// No retry is attempted for 4xx client errors, network errors, or authentication
/// failures — these are not transient.
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Number of additional attempts after the initial request fails.
    /// Default: 3.
    pub max_retries: u32,
    /// Delay before the first retry (and base for exponential backoff).
    /// Default: 1 second.
    pub initial_delay: Duration,
    /// Upper bound on any single inter-retry delay.
    /// Default: 30 seconds.
    pub max_delay: Duration,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            initial_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(30),
        }
    }
}

/// Typed HTTP client for the Uptrakit web API.
///
/// Provides compile-time type safety for all API endpoints by using shared
/// request/response types from `uptrakit-web-api-types`.
pub struct UptrakitClient {
    http: reqwest::Client,
    base_url: String,
    token: Option<String>,
    retry: Option<RetryConfig>,
}

impl UptrakitClient {
    /// Default connect timeout for the HTTP client (10 seconds).
    const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

    /// Default request timeout for the HTTP client (30 seconds).
    const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

    /// Create a new client. Pass `token: None` for unauthenticated endpoints
    /// (e.g. the device authorization flow).
    ///
    /// When `ca_pem` is `Some`, the provided PEM replaces system root
    /// certificates entirely (via `tls_certs_only`). This is the correct
    /// approach for private CA trust — `add_root_certificate` is deprecated
    /// because it appends to rather than replacing system roots.
    ///
    /// `insecure = true` takes precedence over `ca_pem` and disables all TLS
    /// verification. `ca_pem` is ignored when `insecure` is `true`.
    ///
    /// `request_timeout` overrides [`DEFAULT_REQUEST_TIMEOUT`] when `Some`.
    ///
    /// [`DEFAULT_REQUEST_TIMEOUT`]: Self::DEFAULT_REQUEST_TIMEOUT
    pub fn new(
        base_url: &str,
        token: Option<&str>,
        insecure: bool,
        ca_pem: Option<&str>,
        request_timeout: Option<Duration>,
    ) -> Result<Self> {
        let timeout = request_timeout.unwrap_or(Self::DEFAULT_REQUEST_TIMEOUT);
        let mut builder = reqwest::Client::builder()
            .connect_timeout(Self::DEFAULT_CONNECT_TIMEOUT)
            .timeout(timeout);
        if insecure {
            builder = builder.tls_danger_accept_invalid_certs(true);
        } else if let Some(pem) = ca_pem {
            let cert = reqwest::Certificate::from_pem(pem.as_bytes()).context_to()?;
            builder = builder.tls_certs_only(std::iter::once(cert));
        }
        let http = builder.build().context_to()?;

        Ok(Self {
            http,
            base_url: base_url.trim_end_matches('/').to_string(),
            token: token.map(|t| t.to_string()),
            retry: None,
        })
    }

    /// Create a client with a required bearer token.
    ///
    /// When `ca_pem` is `Some`, the provided PEM replaces system root
    /// certificates (see [`Self::new`] for details).
    pub fn with_token(
        base_url: &str,
        token: &str,
        insecure: bool,
        ca_pem: Option<&str>,
    ) -> Result<Self> {
        Self::new(base_url, Some(token), insecure, ca_pem, None)
    }

    /// Enable automatic retry on transient failures (429 and 5xx).
    ///
    /// Returns a new client with the given retry configuration. By default,
    /// the client fails fast with no retries. Retries use exponential backoff
    /// for 5xx errors and respect `Retry-After` headers for 429 errors.
    pub fn with_retry(mut self, config: RetryConfig) -> Self {
        self.retry = Some(config);
        self
    }

    /// Execute a raw (untyped) API request. Used by the CLI `api` escape-hatch command.
    pub async fn raw_request(
        &self,
        method: &str,
        path: &str,
        body: Option<serde_json::Value>,
    ) -> Result<RawResponse> {
        let url = format!("{}{}", self.base_url, path);
        let method = method.to_uppercase();
        let req_method = method
            .parse::<reqwest::Method>()
            .map_err(|e| report!(ClientError::InvalidMethod(e.to_string())))?;

        let mut req = self.http.request(req_method, &url);
        if let Some(token) = &self.token {
            req = req.bearer_auth(token);
        }
        if let Some(body) = body {
            req = req.json(&body);
        }

        let resp = req.send().await.context_to()?;
        let status = resp.status();
        let text = resp.text().await.context_to()?;

        let body = if text.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text))
        };

        Ok(RawResponse { status, body })
    }

    // ── Internal helpers ──────────────────────────────────────────────

    fn token_or_err(&self) -> Result<&str> {
        self.token
            .as_deref()
            .ok_or_else(|| report!(ClientError::NotAuthenticated))
    }

    /// Send a request, retrying automatically on 429 and 5xx responses.
    ///
    /// Without a [`RetryConfig`] (the default), this is a direct single-shot
    /// `send()`. Retries use exponential backoff (5xx) or the `Retry-After`
    /// header (429). 4xx and network errors are never retried.
    async fn send_with_retry(&self, req: reqwest::RequestBuilder) -> Result<reqwest::Response> {
        let Some(retry) = &self.retry else {
            return req.send().await.context_to();
        };

        // Pre-clone the builder for every potential retry before the first send
        // consumes it. `try_clone` returns `None` for streaming bodies; the
        // collected vec will just be shorter, reducing effective retry count.
        let retry_builders: Vec<reqwest::RequestBuilder> = (0..retry.max_retries)
            .map_while(|_| req.try_clone())
            .collect();

        let mut resp = req.send().await.context_to()?;

        for (attempt, retry_req) in retry_builders.into_iter().enumerate() {
            let status = resp.status();
            let delay = if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
                // Respect Retry-After header; fall back to initial_delay.
                parse_retry_after(&resp)
                    .map(Duration::from_secs)
                    .unwrap_or(retry.initial_delay)
                    .min(retry.max_delay)
            } else if status.is_server_error() {
                // Exponential backoff: initial, 2×initial, 4×initial, …, capped.
                let factor = 1u32.checked_shl(attempt as u32).unwrap_or(u32::MAX);
                retry
                    .initial_delay
                    .saturating_mul(factor)
                    .min(retry.max_delay)
            } else {
                // Not retriable — return as-is.
                return Ok(resp);
            };

            tokio::time::sleep(delay).await;
            resp = retry_req.send().await.context_to()?;
        }

        Ok(resp)
    }

    /// Fetch all pages from a paginated list endpoint, accumulating every item.
    ///
    /// Serialises `base_query` to JSON, then overrides `page` and `per_page`
    /// (set to [`MAX_PER_PAGE`]) on each iteration. Stops when
    /// `page >= total_pages` or the first page reports zero total pages.
    ///
    /// [`MAX_PER_PAGE`]: uptrakit_web_api_types::pagination::MAX_PER_PAGE
    pub(crate) async fn fetch_all_pages<T: DeserializeOwned + Send>(
        &self,
        path: &str,
        base_query: &impl Serialize,
    ) -> Result<Vec<T>> {
        use crate::types_impl::pagination::{MAX_PER_PAGE, PaginatedResponse};

        let base_value = serde_json::to_value(base_query).context_to()?;
        let mut all: Vec<T> = Vec::new();
        let mut page: u64 = 1;
        loop {
            let mut query = base_value.clone();
            if let Some(obj) = query.as_object_mut() {
                obj.insert("page".to_string(), serde_json::json!(page));
                obj.insert("per_page".to_string(), serde_json::json!(MAX_PER_PAGE));
            }
            let resp: PaginatedResponse<T> = self.get_with_query(path, &query).await?;
            let total_pages = resp.total_pages;
            all.extend(resp.items);
            if page >= total_pages || total_pages == 0 {
                break;
            }
            page += 1;
        }
        Ok(all)
    }

    async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.get(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn get_with_query<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &impl Serialize,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .get(&url)
            .bearer_auth(self.token_or_err()?)
            .query(query);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn post_json<T: DeserializeOwned>(&self, path: &str, body: &impl Serialize) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .post(&url)
            .bearer_auth(self.token_or_err()?)
            .json(body);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn post_empty<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.post(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    /// POST without authentication (for device auth endpoints).
    async fn post_json_unauth<T: DeserializeOwned>(
        &self,
        path: &str,
        body: &impl Serialize,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.post(&url).json(body);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    /// POST a form-urlencoded body without authentication (OAuth endpoints).
    ///
    /// On HTTP 200, deserialise the JSON response body into `T`.
    /// On HTTP 400, try to parse the body as an RFC 6749 §5.2 `OAuthErrorResponse`;
    /// on success, return `Err(ClientError::OAuthError(...))`. If the 400 body is
    /// not a parseable OAuth error envelope, or for any other non-success status,
    /// fall through to `handle_response_bytes` (the shared status-dispatcher) so
    /// `RateLimited` (429), `NotAuthenticated` (401), `NotFound` (404), and
    /// generic `Api { status, message }` still flow through one place.
    async fn post_form_unauth<T: DeserializeOwned, F: Serialize + ?Sized>(
        &self,
        path: &str,
        form: &F,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.post(&url).form(form);
        let resp = self.send_with_retry(req).await?;

        let status = resp.status();
        // Extract Retry-After while the response is still alive — the bytes
        // helper cannot reconstruct headers from the body.
        let retry_after = parse_retry_after(&resp);
        let bytes = resp.bytes().await.context_to()?;

        if status == reqwest::StatusCode::OK {
            return serde_json::from_slice::<T>(&bytes).context_to();
        }
        if status == reqwest::StatusCode::BAD_REQUEST
            && let Ok(err_resp) =
                serde_json::from_slice::<crate::types_impl::oauth::OAuthErrorResponse>(&bytes)
        {
            bail!(ClientError::OAuthError(err_resp));
        }
        // Body did not match the OAuth error envelope — fall through to the
        // shared status-dispatcher so 400 surfaces consistently with every
        // other endpoint.

        self.handle_response_bytes(status, bytes.to_vec(), retry_after)
            .await
    }

    async fn delete(&self, path: &str) -> Result<()> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.delete(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        self.handle_empty_response(resp).await
    }

    /// POST with no body, expecting `204 No Content`.
    async fn post_empty_no_content(&self, path: &str) -> Result<()> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.post(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        self.handle_empty_response(resp).await
    }

    async fn delete_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.delete(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    /// DELETE with a JSON body, deserializing the JSON response into `T`.
    ///
    /// Distinct from [`delete_json`](Self::delete_json), which sends no body.
    async fn delete_json_body<T: DeserializeOwned>(
        &self,
        path: &str,
        body: &impl Serialize,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .delete(&url)
            .bearer_auth(self.token_or_err()?)
            .json(body);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn delete_with_query(&self, path: &str, query: &impl Serialize) -> Result<()> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .delete(&url)
            .bearer_auth(self.token_or_err()?)
            .query(query);
        let resp = self.send_with_retry(req).await?;
        self.handle_empty_response(resp).await
    }

    #[expect(
        dead_code,
        reason = "HTTP helper — not yet called by any route but retained for API completeness"
    )]
    async fn delete_with_query_json<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &impl Serialize,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .delete(&url)
            .bearer_auth(self.token_or_err()?)
            .query(query);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn put_json<T: DeserializeOwned>(&self, path: &str, body: &impl Serialize) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .put(&url)
            .bearer_auth(self.token_or_err()?)
            .json(body);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    async fn get_with_etag<T: DeserializeOwned>(&self, path: &str) -> Result<(T, String)> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.get(&url).bearer_auth(self.token_or_err()?);
        let resp = self.send_with_retry(req).await?;
        let etag = resp
            .headers()
            .get(reqwest::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string();
        let body: T = self.handle_response(resp).await?;
        Ok((body, etag))
    }

    async fn put_json_with_etag<T: DeserializeOwned>(
        &self,
        path: &str,
        body: &impl Serialize,
        etag: &str,
    ) -> Result<(T, String)> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .put(&url)
            .bearer_auth(self.token_or_err()?)
            .header(reqwest::header::IF_MATCH, etag)
            .json(body);
        let resp = self.send_with_retry(req).await?;
        let new_etag = resp
            .headers()
            .get(reqwest::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string();
        let body: T = self.handle_response(resp).await?;
        Ok((body, new_etag))
    }

    /// POST with JSON body, expecting a 204 No Content response.
    async fn post_json_no_content(&self, path: &str, body: &impl Serialize) -> Result<()> {
        let url = format!("{}{}", self.base_url, path);
        let req = self
            .http
            .post(&url)
            .bearer_auth(self.token_or_err()?)
            .json(body);
        let resp = self.send_with_retry(req).await?;
        self.handle_empty_response(resp).await
    }

    /// GET without authentication (for public endpoints).
    async fn get_unauth<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.get(&url);
        let resp = self.send_with_retry(req).await?;
        self.handle_response(resp).await
    }

    /// GET without authentication, returning the raw response body as text.
    async fn get_text_unauth(&self, path: &str) -> Result<String> {
        let url = format!("{}{}", self.base_url, path);
        let req = self.http.get(&url);
        let resp = self.send_with_retry(req).await?;
        self.handle_text_response(resp).await
    }

    async fn handle_response<T: DeserializeOwned>(&self, resp: reqwest::Response) -> Result<T> {
        let status = resp.status();
        let retry_after = parse_retry_after(&resp);
        let bytes = resp.bytes().await.context_to()?.to_vec();
        self.handle_response_bytes(status, bytes, retry_after).await
    }

    async fn handle_response_bytes<T: DeserializeOwned>(
        &self,
        status: reqwest::StatusCode,
        bytes: Vec<u8>,
        retry_after: Option<u64>,
    ) -> Result<T> {
        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            bail!(ClientError::RateLimited {
                retry_after_seconds: retry_after,
            });
        }
        if status == reqwest::StatusCode::UNAUTHORIZED {
            bail!(ClientError::NotAuthenticated);
        }
        let text = String::from_utf8_lossy(&bytes).into_owned();
        if status == reqwest::StatusCode::NOT_FOUND {
            let message = extract_error_message(&text);
            bail!(ClientError::NotFound(message));
        }
        if status.is_client_error() || status.is_server_error() {
            let message = extract_error_message(&text);
            bail!(ClientError::Api { status, message });
        }
        serde_json::from_slice::<T>(&bytes).context_to()
    }

    async fn handle_empty_response(&self, resp: reqwest::Response) -> Result<()> {
        let status = resp.status();
        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_after = parse_retry_after(&resp);
            bail!(ClientError::RateLimited {
                retry_after_seconds: retry_after,
            });
        }
        if status == reqwest::StatusCode::UNAUTHORIZED {
            bail!(ClientError::NotAuthenticated);
        }
        if status == reqwest::StatusCode::NOT_FOUND {
            let text = resp.text().await.context_to()?;
            let message = extract_error_message(&text);
            bail!(ClientError::NotFound(message));
        }
        if status.is_client_error() || status.is_server_error() {
            let text = resp.text().await.context_to()?;
            let message = extract_error_message(&text);
            bail!(ClientError::Api { status, message });
        }
        Ok(())
    }

    async fn handle_text_response(&self, resp: reqwest::Response) -> Result<String> {
        let status = resp.status();
        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_after = parse_retry_after(&resp);
            bail!(ClientError::RateLimited {
                retry_after_seconds: retry_after,
            });
        }
        if status == reqwest::StatusCode::UNAUTHORIZED {
            bail!(ClientError::NotAuthenticated);
        }
        let text = resp.text().await.context_to()?;
        if status == reqwest::StatusCode::NOT_FOUND {
            let message = extract_error_message(&text);
            bail!(ClientError::NotFound(message));
        }
        if status.is_client_error() || status.is_server_error() {
            let message = extract_error_message(&text);
            bail!(ClientError::Api { status, message });
        }
        Ok(text)
    }
}

/// Parse the `Retry-After` header from a response as seconds.
///
/// Only the seconds-delay format (e.g. `Retry-After: 60`) is supported.
/// HTTP-date format and non-numeric values return `None`.
fn parse_retry_after(resp: &reqwest::Response) -> Option<u64> {
    resp.headers()
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .parse::<u64>()
        .ok()
}

/// Extract an error message from a JSON response body, falling back to
/// the raw text when the body is not JSON or has no `error` field.
#[expect(
    clippy::indexing_slicing,
    reason = "serde_json::Value index operator returns Value::Null for missing keys rather than panicking; this is safe"
)]
pub(crate) fn extract_error_message(text: &str) -> String {
    serde_json::from_str::<serde_json::Value>(text)
        .ok()
        .and_then(|v| v["error"].as_str().map(|s| s.to_string()))
        .unwrap_or_else(|| {
            if text.is_empty() {
                "Request failed".to_string()
            } else {
                text.to_string()
            }
        })
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::assertions_on_result_states,
        reason = "test assertions — assert!(result.is_err()) is idiomatic in tests"
    )]

    use super::*;

    #[test]
    fn extract_error_message_from_json() {
        let text = r#"{"error":"Not found"}"#;
        assert_eq!(extract_error_message(text), "Not found");
    }

    #[test]
    fn extract_error_message_from_json_without_error_field() {
        let text = r#"{"message":"something"}"#;
        assert_eq!(extract_error_message(text), text);
    }

    #[test]
    fn extract_error_message_from_plain_text() {
        let text = "Internal Server Error";
        assert_eq!(extract_error_message(text), "Internal Server Error");
    }

    #[test]
    fn extract_error_message_from_empty() {
        assert_eq!(extract_error_message(""), "Request failed");
    }

    #[test]
    fn base_url_trailing_slash_is_trimmed() {
        let client = UptrakitClient::new("https://example.com/", None, false, None, None)
            .expect("client creation");
        assert_eq!(client.base_url, "https://example.com");
    }

    #[test]
    fn base_url_without_trailing_slash_is_unchanged() {
        let client = UptrakitClient::new("https://example.com", None, false, None, None)
            .expect("client creation");
        assert_eq!(client.base_url, "https://example.com");
    }

    #[test]
    fn with_token_stores_token() {
        let client = UptrakitClient::with_token("https://example.com", "tok-123", false, None)
            .expect("client creation");
        assert_eq!(client.token.as_deref(), Some("tok-123"));
    }

    #[test]
    fn new_without_token_stores_none() {
        let client = UptrakitClient::new("https://example.com", None, false, None, None)
            .expect("client creation");
        assert!(client.token.is_none());
    }

    #[test]
    fn token_or_err_returns_token_when_present() {
        let client = UptrakitClient::with_token("https://example.com", "tok", false, None)
            .expect("client creation");
        assert_eq!(client.token_or_err().expect("token"), "tok");
    }

    #[test]
    fn token_or_err_returns_error_when_absent() {
        let client = UptrakitClient::new("https://example.com", None, false, None, None)
            .expect("client creation");
        let err = client.token_or_err().unwrap_err();
        assert!(
            matches!(err.current_context(), ClientError::NotAuthenticated),
            "expected NotAuthenticated, got: {err}"
        );
    }

    #[test]
    fn parse_retry_after_valid_seconds() {
        let resp = http::Response::builder()
            .status(http::StatusCode::TOO_MANY_REQUESTS)
            .header("Retry-After", "60")
            .body("")
            .unwrap();
        let reqwest_resp = reqwest::Response::from(resp);
        assert_eq!(parse_retry_after(&reqwest_resp), Some(60));
    }

    #[test]
    fn parse_retry_after_missing_header() {
        let resp = http::Response::builder()
            .status(http::StatusCode::TOO_MANY_REQUESTS)
            .body("")
            .unwrap();
        let reqwest_resp = reqwest::Response::from(resp);
        assert_eq!(parse_retry_after(&reqwest_resp), None);
    }

    #[test]
    fn parse_retry_after_non_numeric() {
        let resp = http::Response::builder()
            .status(http::StatusCode::TOO_MANY_REQUESTS)
            .header("Retry-After", "Wed, 21 Oct 2025 07:28:00 GMT")
            .body("")
            .unwrap();
        let reqwest_resp = reqwest::Response::from(resp);
        assert_eq!(parse_retry_after(&reqwest_resp), None);
    }

    #[test]
    fn raw_response_serialization() {
        let resp = RawResponse {
            status: reqwest::StatusCode::OK,
            body: serde_json::json!({"key": "value"}),
        };
        let json = serde_json::to_string(&resp).expect("serialize");
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(parsed["status"], 200);
        assert_eq!(parsed["body"]["key"], "value");
    }

    #[test]
    fn default_client_has_no_retry() {
        let client =
            UptrakitClient::new("https://example.com", None, false, None, None).expect("client");
        assert!(client.retry.is_none());
    }

    #[test]
    fn with_retry_sets_config() {
        let client = UptrakitClient::new("https://example.com", None, false, None, None)
            .expect("client")
            .with_retry(RetryConfig::default());
        assert!(client.retry.is_some());
    }

    #[test]
    fn retry_config_default_values() {
        let config = RetryConfig::default();
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.initial_delay, Duration::from_secs(1));
        assert_eq!(config.max_delay, Duration::from_secs(30));
    }

    /// Helper: build a client pointing at the given URL with a short retry config.
    #[cfg(test)]
    fn retrying_client(base_url: &str) -> UptrakitClient {
        UptrakitClient::with_token(base_url, "test-token", false, None)
            .expect("client")
            .with_retry(RetryConfig {
                max_retries: 2,
                initial_delay: Duration::from_millis(1),
                max_delay: Duration::from_millis(10),
            })
    }

    // ── Retry behaviour tests ──────────────────────────────────────────

    #[tokio::test]
    async fn retry_exhausted_on_repeated_503() {
        use crate::types_impl::pagination::PaginationParams;
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;
        let mock = server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(503).body(r#"{"error":"down"}"#);
        });

        let params = PaginationParams {
            page: None,
            per_page: None,
        };
        let client = retrying_client(&server.base_url());
        let result = client.list_hosts(&params).await;

        assert!(result.is_err());
        // 1 initial attempt + 2 retries = 3 total calls
        mock.assert_calls(3);
    }

    #[tokio::test]
    async fn no_retry_on_400() {
        use crate::types_impl::pagination::PaginationParams;
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;
        let mock = server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(400).body(r#"{"error":"bad request"}"#);
        });

        let params = PaginationParams {
            page: None,
            per_page: None,
        };
        let client = retrying_client(&server.base_url());
        let result = client.list_hosts(&params).await;

        assert!(result.is_err());
        mock.assert_calls(1); // no retries for client errors
    }

    #[tokio::test]
    async fn no_retry_on_401() {
        use crate::types_impl::pagination::PaginationParams;
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;
        let mock = server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(401).body(r#"{"error":"unauthorized"}"#);
        });

        let params = PaginationParams {
            page: None,
            per_page: None,
        };
        let client = retrying_client(&server.base_url());
        let result = client.list_hosts(&params).await;

        assert!(result.is_err());
        mock.assert_calls(1); // no retries for 401
    }

    #[tokio::test]
    async fn retry_exhausted_on_repeated_429() {
        use crate::types_impl::pagination::PaginationParams;
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;
        let mock = server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(429)
                .header("Retry-After", "1")
                .body(r#"{"error":"rate limited"}"#);
        });

        let params = PaginationParams {
            page: None,
            per_page: None,
        };
        let client = retrying_client(&server.base_url());
        let result = client.list_hosts(&params).await;

        assert!(result.is_err());
        // 1 initial + 2 retries = 3 total calls
        mock.assert_calls(3);
    }

    // ── Pagination tests ──────────────────────────────────────────────

    /// Build a minimal valid `HostResponse`-compatible JSON object.
    fn host_json(id: &str) -> serde_json::Value {
        serde_json::json!({
            "id": id,
            "machine_id": format!("machine-{id}"),
            "hostname": format!("host-{id}"),
            "friendly_name": format!("Host {id}"),
            "os_type": null,
            "os_version": null,
            "architecture": null,
            "ip_address": null,
            "last_seen_at": null,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "agents": [],
            "tags": []
        })
    }

    fn paginated_hosts_json(
        items: Vec<serde_json::Value>,
        total: u64,
        page: u64,
        total_pages: u64,
    ) -> serde_json::Value {
        serde_json::json!({
            "items": items,
            "total": total,
            "page": page,
            "per_page": 1000,
            "total_pages": total_pages
        })
    }

    #[tokio::test]
    async fn list_all_hosts_multi_page() {
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;

        let h1 = host_json("550e8400-e29b-41d4-a716-446655440001");
        let h2 = host_json("550e8400-e29b-41d4-a716-446655440002");
        let h3 = host_json("550e8400-e29b-41d4-a716-446655440003");

        server.mock(|when, then| {
            when.method(GET)
                .path("/api/v1/hosts")
                .query_param("page", "1")
                .query_param("per_page", "1000");
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![h1.clone()], 3, 1, 3));
        });
        server.mock(|when, then| {
            when.method(GET)
                .path("/api/v1/hosts")
                .query_param("page", "2")
                .query_param("per_page", "1000");
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![h2.clone()], 3, 2, 3));
        });
        server.mock(|when, then| {
            when.method(GET)
                .path("/api/v1/hosts")
                .query_param("page", "3")
                .query_param("per_page", "1000");
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![h3.clone()], 3, 3, 3));
        });

        let client =
            UptrakitClient::with_token(&server.base_url(), "tok", false, None).expect("client");
        let all = client.list_all_hosts().await.expect("list_all_hosts");
        assert_eq!(all.len(), 3);
        assert_eq!(
            all[0].machine_id,
            "machine-550e8400-e29b-41d4-a716-446655440001"
        );
        assert_eq!(
            all[2].machine_id,
            "machine-550e8400-e29b-41d4-a716-446655440003"
        );
    }

    #[tokio::test]
    async fn list_all_hosts_single_page() {
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;
        let h1 = host_json("550e8400-e29b-41d4-a716-000000000001");
        let h2 = host_json("550e8400-e29b-41d4-a716-000000000002");

        server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![h1, h2], 2, 1, 1));
        });

        let client =
            UptrakitClient::with_token(&server.base_url(), "tok", false, None).expect("client");
        let all = client.list_all_hosts().await.expect("list_all_hosts");
        assert_eq!(all.len(), 2);
    }

    #[tokio::test]
    async fn list_all_hosts_empty() {
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;

        server.mock(|when, then| {
            when.method(GET).path("/api/v1/hosts");
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![], 0, 1, 0));
        });

        let client =
            UptrakitClient::with_token(&server.base_url(), "tok", false, None).expect("client");
        let all = client.list_all_hosts().await.expect("list_all_hosts");
        assert!(all.is_empty());
    }

    #[tokio::test]
    async fn list_all_hosts_forwards_page_params() {
        use crate::types_impl::pagination::MAX_PER_PAGE;
        use httpmock::prelude::*;

        let server = MockServer::start_async().await;

        // Verify that page=1 and per_page=MAX_PER_PAGE are sent
        let page_param_mock = server.mock(|when, then| {
            when.method(GET)
                .path("/api/v1/hosts")
                .query_param("page", "1")
                .query_param("per_page", MAX_PER_PAGE.to_string());
            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(paginated_hosts_json(vec![], 0, 1, 0));
        });

        let client =
            UptrakitClient::with_token(&server.base_url(), "tok", false, None).expect("client");
        client.list_all_hosts().await.expect("list_all_hosts");

        page_param_mock.assert_calls(1);
    }

    #[test]
    fn new_with_ca_pem_none_succeeds() {
        let client =
            UptrakitClient::new("https://example.com", None, false, None, None).expect("client");
        assert!(client.token.is_none());
    }

    #[test]
    fn new_with_insecure_ignores_invalid_ca_pem() {
        // insecure=true skips ca_pem parsing entirely — no error even for garbage PEM
        let client =
            UptrakitClient::new("https://example.com", None, true, Some("not-a-pem"), None);
        assert!(client.is_ok());
    }
}