deboa 0.1.0-beta.8

A friendly rest client on top of hyper.
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! # Deboa - Core API Documentation
//!
//! Hello, and welcome to the core Deboa API documentation!
//!
//! This API documentation is highly technical and is purely a reference.
//!
//! Depend on `deboa` in `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! deboa = "0.1.0"
//! ```
//!
//! <small>Note that development versions, tagged with `-dev`, are not published
//! and need to be specified as [git dependencies].</small>
//!
//! ``` rust,ignore
//! use deboa::{Client, Result, errors::DeboaError, request::DeboaRequest};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     let mut client = Client::builder()
//!         .build();
//!
//!     let response = DeboaRequest::get("https://httpbin.org/get")?
//!         .send_with(&mut client)
//!         .await?;
//!
//!     println!("Response: {:#?}", response);
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Features
//!
//! To avoid compiling unused dependencies, Deboa feature-gates optional
//! functionality, some enabled by default:
//!
//! | Feature           | Default? | Description                                             |
//! |-------------------|----------|---------------------------------------------------------|
//! | `tokio_rt`        | Yes      | Support tokio runtime (enabled by default).             |
//! | `smol_rt`         | No       | Support smol runtime.                                   |
//! | `http1`           | No       | Support for HTTP/1.                                     |
//! | `http2`           | Yes      | Support for HTTP/2 (enabled by default).                |
//! | `http3`           | No       | Support for HTTP/3.                                     |
//! | `http3-smol`      | No       | Support for HTTP/3 on Smol.                             |
//! | `tokio-rust-tls`  | Yes      | Support for tokio-rust-tls (enabled by default).        |
//! | `tokio-native-tls`| No       | Support for tokio-native-tls.                           |
//! | `smol-rust-tls`   | No       | Support for smol-rust-tls.                              |
//! | `smol-native-tls` | No       | Support for smol-native-tls.                            |
//!
//! Disabled features can be selectively enabled in `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! deboa = { version = "0.1.0", features = ["tokio_rt", "http2", "tokio-rust-tls"] }
//! ```
//!
//! Conversely, HTTP/2 can be disabled:
//!
//! ```toml
//! [dependencies]
//! deboa = { version = "0.1.0", default-features = false }
//! ```
//!

#[cfg(all(feature = "tokio-native-tls", feature = "http3"))]
compile_error!("HTTP3 is not supported within tokio-native-tls runtime.");

#[cfg(all(feature = "smol-native-tls", feature = "http3"))]
compile_error!("HTTP3 is not supported within smol-native-tls runtime.");

#[cfg(all(feature = "tokio-rt", feature = "smol-rt", feature = "compio-rt"))]
compile_error!("Only one runtime feature can be enabled at a time.");

#[cfg(not(any(feature = "http1", feature = "http2", feature = "http3")))]
compile_error!("At least one HTTP version feature must be enabled.");

pub(crate) const MAX_ERROR_MESSAGE_SIZE: usize = 50000;

#[cfg(any(feature = "tokio-rust-tls", feature = "smol-rust-tls", feature = "compio-rust-tls"))]
#[inline]
pub(crate) fn alpn() -> Vec<Vec<u8>> {
    vec![
        #[cfg(feature = "http2")]
        b"h2".to_vec(),
        #[cfg(feature = "http1")]
        b"http/1.1".to_vec(),
        #[cfg(feature = "http3")]
        b"h3".to_vec(),
    ]
}

#[cfg(any(
    feature = "tokio-native-tls",
    feature = "smol-native-tls",
    feature = "compio-native-tls"
))]
#[inline]
pub(crate) fn alpn() -> &'static [&'static str] {
    &[
        #[cfg(feature = "http2")]
        "h2",
        #[cfg(feature = "http1")]
        "http/1.1",
        #[cfg(feature = "http3")]
        "h3",
    ]
}

use cfg_if::cfg_if;

#[cfg(feature = "tokio-rt")]
use tokio::sync::{RwLock, RwLockWriteGuard};

#[cfg(feature = "smol-rt")]
use smol::lock::RwLock;

#[cfg(feature = "compio-rt")]
use std::sync::Mutex;

use std::fmt::{Debug, Display};
use std::net::IpAddr;
use std::ops::Shl;

use http::{header, HeaderValue, Request};
use log::{error, info};

use crate::cert::{Certificate, Identity};

use crate::client::conn::ConnectionConfig;

use crate::catcher::DeboaCatcher;
use crate::client::conn::pool::{DeboaHttpConnectionPool, HttpConnectionPool};
use crate::errors::{DeboaError, RequestError};
use crate::request::{DeboaRequest, IntoRequest};
use crate::response::DeboaResponse;

pub use async_trait::async_trait;

#[cfg(feature = "tokio-rt")]
pub type File = tokio::fs::File;
#[cfg(feature = "smol-rt")]
pub type File = smol::fs::File;
#[cfg(feature = "compio-rt")]
pub type File = compio_fs::File;

pub mod cache;
pub mod catcher;
pub mod cert;
pub mod client;
pub mod cookie;
pub mod errors;
pub mod form;
pub mod fs;
pub mod request;
pub mod response;
pub mod rt;
pub mod url;

#[cfg(test)]
mod tests;

/// Type alias for Result<T, DeboaError>
/// Convenience alias for handling Deboa errors throughout the library.
///
/// # Examples
///
/// ```
/// use deboa::Result;
///
/// fn example() -> Result<String> {
///     Ok("success".to_string())
/// }
/// ```
///
/// # See Also
/// - [DeboaError](crate::errors::DeboaError)
pub type Result<T> = std::result::Result<T, DeboaError>;

///
/// Extension trait for Client to enable the `<<` operator for URL construction.
/// This allows for a more ergonomic way to create requests using the `<<` operator.
/// The operator creates a GET request with the provided URL.
///
/// # Examples
///
/// ``` rust,ignore
/// use deboa::{Client, Result};
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let client = Client::new();
///     let request = &client << "https://httpbin.org/get";
///     // do something with the request
///     Ok(())
/// }
/// ```
///
/// # Notes
/// - This implementation is primarily for convenience and ergonomics
/// - For more complex request configurations, use the full DeboaRequest API
/// - The `<<` operator is a shorthand for creating GET requests
impl Shl<&str> for &Client {
    type Output = DeboaRequest;

    fn shl(self, other: &str) -> Self::Output {
        DeboaRequest::get(other)
            .expect("Invalid URL!")
            .build()
            .expect("Invalid request!")
    }
}

#[derive(PartialEq, Debug, Clone)]
/// Enum that represents the HTTP version.
///
/// # Variants
///
/// * `Http1` - The HTTP/1.1 version.
/// * `Http2` - The HTTP/2 version.
pub enum HttpVersion {
    #[cfg(feature = "http1")]
    Http1,
    #[cfg(feature = "http2")]
    Http2,
    #[cfg(feature = "http3")]
    Http3,
}

impl Display for HttpVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "http1")]
            HttpVersion::Http1 => write!(f, "HTTP/1.1"),
            #[cfg(feature = "http2")]
            HttpVersion::Http2 => write!(f, "HTTP/2"),
            #[cfg(feature = "http3")]
            HttpVersion::Http3 => write!(f, "HTTP/3"),
        }
    }
}

#[deprecated(note = "DeboaBuilder is now ClientBuilder")]
pub type DeboaBuilder = ClientBuilder;

/// A builder for configuring and creating a new `Deboa` client instance.
///
/// This builder allows you to configure various aspects of the HTTP client before
/// constructing it. You can set timeouts, configure protocols, add error handlers,
/// and more.
///
/// # Examples
///
/// ``` rust,ignore
/// use deboa::{Client, Result, HttpVersion};
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///   let client = Client::builder()
///     .connection_timeout(30)  // 30 seconds
///     .request_timeout(10)     // 10 seconds
///     .protocol(HttpVersion::Http2)  // Use HTTP/2
///     .build();
///
///   // Use the client to make requests...
///   Ok(())
/// }
/// ```
///
/// # Default Configuration
///
/// - Connection timeout: 30 seconds
/// - Request timeout: 30 seconds
/// - Protocol: HTTP/1.1
/// - No client certificates
/// - No custom error catchers
pub struct ClientBuilder {
    connection_timeout: u64,
    request_timeout: u64,
    identity: Option<Identity>,
    certificate: Option<Certificate>,
    catchers: Option<Vec<Box<dyn DeboaCatcher>>>,
    protocol: HttpVersion,
    skip_cert_verification: bool,
    #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
    pool: RwLock<HttpConnectionPool>,
    #[cfg(feature = "compio-rt")]
    pool: Mutex<HttpConnectionPool>,
    bind_addr: IpAddr,
}

impl ClientBuilder {
    /// Sets the maximum duration to wait when connecting to a server.
    ///
    /// This timeout affects the initial TCP connection establishment. If the server
    /// doesn't respond within this duration, the connection will fail with a timeout error.
    ///
    /// # Arguments
    ///
    /// * `connection_timeout` - The timeout in seconds.
    ///
    /// # Examples
    ///
    /// ``` rust, no_run
    /// use deboa::Client;
    /// let builder = Client::builder()
    ///     .connection_timeout(10);  // 10 seconds
    /// ```
    ///
    /// # Note
    /// A value of 0 means no timeout (not recommended in production).
    #[inline]
    pub fn connection_timeout(mut self, connection_timeout: u64) -> Self {
        self.connection_timeout = connection_timeout;
        self
    }

    /// Sets the maximum duration for the entire HTTP request/response cycle.
    ///
    /// This includes connection time, request writing, server processing, and response reading.
    /// If the entire operation takes longer than this duration, it will be aborted.
    ///
    /// # Arguments
    ///
    /// * `request_timeout` - The timeout in seconds.
    ///
    /// # Examples
    ///
    /// ``` rust, no_run
    /// use deboa::Client;
    /// let builder = Client::builder()
    ///     .request_timeout(30);  // 30 seconds
    /// ```
    ///
    /// # Note
    /// A value of 0 means no timeout (not recommended in production).
    #[inline]
    pub fn request_timeout(mut self, request_timeout: u64) -> Self {
        self.request_timeout = request_timeout;
        self
    }

    /// Configures a client certificate for mutual TLS authentication.
    ///
    /// This is used when the server requires client certificate authentication.
    /// The certificate should be in PEM format and include both the certificate
    /// and private key.
    ///
    /// # Arguments
    ///
    /// * `client_cert` - The client certificate configuration.
    ///
    /// # Examples
    ///
    /// ``` compile_fail
    /// use deboa::{Client, Result, Identity};
    ///
    /// #[tokio::main]
    ///
    /// async fn main() -> Result<()> {
    ///     let cert = Identity::from_pem_file("client.pem")?;
    ///     let builder = Client::builder()
    ///         .set_identity(cert);
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn client_cert(mut self, client_cert: Identity) -> Self {
        self.identity = Some(client_cert);
        self
    }

    /// Configures a client certificate for mutual TLS authentication.
    ///
    /// This is used when the server requires client certificate authentication.
    /// The certificate should be in PEM format and include both the certificate
    /// and private key.
    ///
    /// # Arguments
    ///
    /// * `identity` - The client certificate file.
    ///
    /// # Examples
    ///
    /// ``` compile_fail
    /// use deboa::{Client, Identity, Result};
    ///
    /// #[tokio::main]
    ///
    /// async fn main() -> Result<()> {
    ///     let cert = Identity::new("client.pem", Some("pw"))?;
    ///     let builder = Client::builder()
    ///         .identity(cert);
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn identity(mut self, identity: Identity) -> Self {
        self.identity = Some(identity);
        self
    }

    /// Configures a ca certificate.
    ///
    /// # Arguments
    ///
    /// * `certificate` - The ca certificate file.
    ///
    /// # Examples
    ///
    /// ``` compile_fail
    /// use deboa::{Client, Certificate, Result};
    ///
    /// #[tokio::main]
    ///
    /// async fn main() -> Result<()> {
    ///     let cert = Certificate::new("client.pem")?;
    ///     let builder = Client::builder()
    ///         .certificate(cert);
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn certificate(mut self, certificate: Certificate) -> Self {
        self.certificate = Some(certificate);
        self
    }

    /// Adds an error handler for specific types of errors.
    ///
    /// Catchers are called when an error occurs during request execution.
    /// They can be used to implement custom error handling logic, such as
    /// automatic retries, logging, or error transformation.
    ///
    /// # Arguments
    ///
    /// * `catcher` - A function or closure that handles specific error types.
    ///
    /// # Examples
    ///
    /// ## Automatic Retries
    ///
    /// ```ignore
    /// use deboa::{Client, Result, catcher::DeboaCatcher, request::DeboaRequest, response::DeboaResponse};
    ///
    /// struct AddAuthorization;
    ///
    /// #[deboa::async_trait]
    /// impl DeboaCatcher for AddAuthorization {
    ///     async fn on_request(&self, request: &mut DeboaRequest) -> Result<Option<DeboaResponse>> {
    ///         println!("Request: {:?}", request.url());
    ///         Ok(None)
    ///     }
    ///
    ///     async fn on_response(&self, response: &mut DeboaResponse) -> Result<()> {
    ///         println!("Response: {:?}", response.status());
    ///         Ok(())
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let client = Client::builder()
    ///         .catch(AddAuthorization)
    ///         .build();
    ///     Ok(())
    /// }
    /// ```
    pub fn catch<C: DeboaCatcher>(mut self, catcher: C) -> Self {
        if let Some(catchers) = &mut self.catchers {
            catchers.push(Box::new(catcher));
        } else {
            self.catchers = Some(vec![Box::new(catcher)]);
        }
        self
    }

    /// Sets the HTTP protocol version to use for requests.
    ///
    /// By default, the client will use HTTP/1.1. You can choose to use HTTP/2
    /// for better performance, especially for multiple requests to the same server.
    ///
    /// # Arguments
    ///
    /// * `protocol` - The HTTP protocol version to use.
    ///
    /// # Examples
    ///
    /// ``` rust,ignore
    /// use deboa::{Client, HttpVersion};
    ///
    /// let builder = Client::builder()
    ///     .protocol(HttpVersion::Http2);  // Use HTTP/2
    /// ```
    ///
    /// # Note
    /// The actual protocol version used may be negotiated with the server
    /// during the TLS handshake.
    #[inline]
    pub fn protocol(mut self, protocol: HttpVersion) -> Self {
        self.protocol = protocol;
        self
    }

    /// Skip certificate verification.
    ///
    /// # Arguments
    ///
    /// * `skip` - Whether to skip certificate verification.
    ///
    /// # Examples
    ///
    /// ``` rust, no_run
    /// use deboa::Client;
    ///
    /// let builder = Client::builder()
    ///     .skip_cert_verification(true);  // Skip certificate verification
    /// ```
    ///
    /// # Warning
    /// This should only be used in development or testing environments.
    /// Never use this in production as it makes your application vulnerable to man-in-the-middle attacks.
    ///
    /// # Note
    /// This setting affects all connections made by the client.
    /// It is recommended to use this only for testing purposes.
    ///
    /// # Safety
    /// This function bypasses SSL certificate validation, which can expose your application to security risks.
    /// Only use this in controlled environments where you trust all network traffic.
    ///
    #[inline]
    pub fn skip_cert_verification(mut self, skip: bool) -> Self {
        self.skip_cert_verification = skip;
        self
    }

    /// Set a connection pool.
    ///
    /// # Arguments
    ///
    /// * `pool` - The connection pool to use.
    ///
    /// # Returns
    ///
    /// * `Self` - The builder.
    ///
    /// # Example
    ///
    /// ```compile_fail
    /// use deboa::Client;
    ///
    /// let client = Client::builder()
    ///     .pool(HttpConnectionPool::default())
    ///     .build();
    /// ```
    #[cfg(feature = "compio-rt")]
    #[inline]
    pub fn pool(mut self, pool: HttpConnectionPool) -> Self {
        self.pool = Mutex::new(pool);
        self
    }

    #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
    pub fn pool(mut self, pool: HttpConnectionPool) -> Self {
        self.pool = RwLock::new(pool);
        self
    }

    #[inline]
    pub fn bind_addr(mut self, bind_addr: IpAddr) -> Self {
        self.bind_addr = bind_addr;
        self
    }

    /// Constructs a new `Deboa` client with the configured settings.
    ///
    /// This consumes the builder and returns a new `Deboa` instance that can
    /// be used to make HTTP requests.
    ///
    /// # Returns
    ///
    /// A new `Deboa` client instance.
    ///
    /// # Examples
    ///
    /// ``` rust,ignore
    /// use deboa::{Client, Result};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let client = Client::builder()
    ///     .connection_timeout(10)
    ///     .request_timeout(30)
    ///     .build();
    ///
    ///   // client is now ready to make requests
    ///   Ok(())
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// This method may panic if the underlying HTTP client cannot be created
    /// with the specified configuration.
    #[inline]
    pub fn build(self) -> Client {
        Client {
            connection_timeout: self.connection_timeout,
            request_timeout: self.request_timeout,
            identity: self.identity,
            certificate: self.certificate,
            catchers: self.catchers,
            protocol: self.protocol,
            skip_cert_verification: self.skip_cert_verification,
            pool: self.pool,
            bind_addr: self.bind_addr,
        }
    }
}

#[deprecated(note = "Deboa is now Client")]
pub type Deboa = Client;

/// The main HTTP client for making requests.
///
/// `Deboa` is a flexible and efficient HTTP client that supports both synchronous
/// and asynchronous operations. It provides a builder pattern for configuration
/// and supports features like connection pooling, timeouts, and custom error handling.
///
/// # Features
///
/// - Connection pooling for better performance
/// - Configurable timeouts
/// - Custom error handling with catchers
/// - Support for multiple HTTP protocols (HTTP/1.1, HTTP/2)
/// - Thread-safe and `Send` + `Sync`
///
/// # Examples
///
/// ## Basic Usage
///
/// ``` ignore
/// use deboa::{Client, Result};
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///   // Create a new client with default settings
///   let client = Client::new();
///
///   // Or configure with custom settings
///   let client = Client::builder()
///     .connection_timeout(10)  // 10 seconds
///     .request_timeout(30)     // 30 seconds
///     .build();
///   Ok(())
/// }
/// ```
///
/// # Thread Safety
///
/// `Deboa` implements `Send` and `Sync`, making it safe to share between threads.
/// The connection pool is managed internally and optimized for concurrent access.
///
/// # Performance
///
/// - Connection pooling reduces latency for repeated requests to the same host
/// - Automatic connection reuse when possible
/// - Configurable timeouts prevent hanging requests
pub struct Client {
    connection_timeout: u64,
    request_timeout: u64,
    identity: Option<Identity>,
    certificate: Option<Certificate>,
    catchers: Option<Vec<Box<dyn DeboaCatcher>>>,
    protocol: HttpVersion,
    skip_cert_verification: bool,
    #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
    pool: RwLock<HttpConnectionPool>,
    #[cfg(feature = "compio-rt")]
    pool: Mutex<HttpConnectionPool>,
    bind_addr: IpAddr,
}

impl AsRef<Client> for Client {
    fn as_ref(&self) -> &Client {
        self
    }
}

impl AsMut<Client> for Client {
    fn as_mut(&mut self) -> &mut Client {
        self
    }
}

impl Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("connection_timeout", &self.connection_timeout)
            .field("request_timeout", &self.request_timeout)
            .field("protocol", &self.protocol)
            .finish()
    }
}

pub(crate) const fn default_protocol() -> HttpVersion {
    cfg_if! {
        if #[cfg(feature = "http1")] {
            HttpVersion::Http1
        } else if #[cfg(feature = "http2")] {
            HttpVersion::Http2
        } else {
            HttpVersion::Http3
        }
    }
}

impl Default for Client {
    fn default() -> Self {
        Self {
            connection_timeout: 0,
            request_timeout: 0,
            identity: None,
            certificate: None,
            catchers: None,
            protocol: default_protocol(),
            skip_cert_verification: false,
            #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
            pool: RwLock::new(HttpConnectionPool::default()),
            #[cfg(feature = "compio-rt")]
            pool: Mutex::new(HttpConnectionPool::default()),
            bind_addr: "0.0.0.0"
                .parse()
                .unwrap(),
        }
    }
}

impl Client {
    /// Creates a new `Deboa` instance with default settings.
    ///
    /// This is equivalent to calling `Deboa::builder().build()` and provides
    /// a quick way to get started with sensible defaults.
    ///
    /// # Default Configuration
    ///
    /// - Connection timeout: 30 seconds
    /// - Request timeout: 30 seconds
    /// - Protocol: HTTP/1.1
    /// - No client certificates
    /// - No custom error catchers
    ///
    /// # Returns
    ///
    /// A new `Client` instance with default settings.
    ///
    /// # Examples
    ///
    /// ``` rust,ignore
    /// use deboa::{Client, Result};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let client = Client::new();
    ///   // client is ready to make requests
    ///   Ok(())
    /// }
    /// ```
    ///
    /// # Deprecated
    ///
    /// This method is deprecated and will be removed in a future release. Use `Client::default()` instead.
    ///
    /// # See Also
    ///
    /// - [`Client::builder()`] for custom configuration
    /// - [`Client::default()`] for the same functionality via the `Default` trait
    #[deprecated(note = "Use Client::default() instead", since = "0.0.9")]
    pub fn new() -> Self {
        Self {
            connection_timeout: 0,
            request_timeout: 0,
            identity: None,
            certificate: None,
            catchers: None,
            protocol: default_protocol(),
            skip_cert_verification: false,
            #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
            pool: RwLock::new(HttpConnectionPool::default()),
            #[cfg(feature = "compio-rt")]
            pool: Mutex::new(HttpConnectionPool::default()),
            bind_addr: "0.0.0.0"
                .parse()
                .unwrap(),
        }
    }

    /// Allow create a new Deboa instance.
    ///
    /// # Returns
    ///
    /// * `ClientBuilder` - The new ClientBuilder instance.
    ///
    #[inline]
    pub fn builder() -> ClientBuilder {
        ClientBuilder {
            connection_timeout: 0,
            request_timeout: 0,
            identity: None,
            certificate: None,
            catchers: None,
            protocol: default_protocol(),
            skip_cert_verification: false,
            #[cfg(feature = "compio-rt")]
            pool: Mutex::new(HttpConnectionPool::default()),
            #[cfg(any(feature = "tokio-rt", feature = "smol-rt"))]
            pool: RwLock::new(HttpConnectionPool::default()),
            bind_addr: "0.0.0.0"
                .parse()
                .unwrap(),
        }
    }

    /// Check if certificate verification is skipped.
    ///
    /// # Returns
    ///
    /// * `bool` - `true` if certificate verification is skipped, `false` otherwise.
    #[inline]
    pub fn skip_cert_verification(&self) -> bool {
        self.skip_cert_verification
    }

    /// Allow get protocol at any time.
    ///
    /// # Returns
    ///
    /// * `&HttpVersion` - The protocol.
    ///
    #[inline]
    pub fn protocol(&self) -> &HttpVersion {
        &self.protocol
    }

    /// Allow get request connection timeout at any time.
    ///
    /// # Returns
    ///
    /// * `u64` - The timeout.
    ///
    #[inline]
    pub fn connection_timeout(&self) -> u64 {
        self.connection_timeout
    }

    /// Allow get connection pool at any time.
    ///
    /// # Returns
    ///
    /// * `Option<std::cell::Ref<'_, HttpConnectionPool>>` - The connection pool.
    ///
    #[inline]
    #[cfg(feature = "tokio-rt")]
    pub async fn connection_pool(&self) -> &tokio::sync::RwLock<HttpConnectionPool> {
        &self.pool
    }

    #[inline]
    #[cfg(feature = "smol-rt")]
    pub async fn connection_pool(&self) -> &smol::lock::RwLock<HttpConnectionPool> {
        &self.pool
    }

    #[inline]
    pub fn bind_addr(&self) -> IpAddr {
        self.bind_addr
    }

    /// Allow get request request timeout at any time.
    ///
    /// # Returns
    ///
    /// * `u64` - The timeout.
    ///
    #[inline]
    pub fn request_timeout(&self) -> u64 {
        self.request_timeout
    }

    /// Allow get client certificate at any time.
    ///
    /// # Returns
    ///
    /// * `Option<ClientCert>` - The client certificate.
    ///
    #[inline]
    #[deprecated(note = "Use identity instead", since = "0.0.8")]
    pub fn client_cert(&self) -> Option<&Identity> {
        self.identity
            .as_ref()
    }

    /// Allow get identity at any time.
    ///
    /// # Returns
    ///
    /// * `Option<Identity>` - The identity.
    ///
    #[inline]
    pub fn identity(&self) -> Option<&Identity> {
        self.identity
            .as_ref()
    }

    /// Executes an HTTP request and returns the response.
    ///
    /// This is the primary method for making HTTP requests. It handles the entire
    /// request/response lifecycle, including retries, error handling, and response processing.
    ///
    /// # Arguments
    ///
    /// * `request` - The request to execute. This can be:
    ///   - A string URL (for GET requests)
    ///   - A `DeboaRequest` instance (for more control)
    ///   - Any type that implements `IntoRequest`
    ///
    /// # Returns
    ///
    /// A `Result` containing either:
    /// - `Ok(DeboaResponse)` - The successful HTTP response
    /// - `Err(DeboaError)` - If the request fails or encounters an error
    ///
    /// # Examples
    ///
    /// ## Simple GET Request
    ///
    /// ```rust,ignore
    /// use deboa::{Client, Result};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let mut client = Client::new();
    ///   let response = client.execute("https://httpbin.org/get").await?;
    ///   println!("Status: {}", response.status());
    ///   println!("Body: {}", response.text().await?);
    ///   Ok(())
    /// }
    /// ```
    ///
    /// ## POST Request with JSON Body
    ///
    /// ```rust,ignore
    /// use deboa::{Client, Result, request::post};
    /// use serde_json::json;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let mut client = Client::new();
    ///   let response = client
    ///     .execute(
    ///         post("https://httpbin.org/post")
    ///             .text("text")?
    ///     )
    ///     .await?;
    ///   Ok(())
    /// }
    /// ```
    ///
    /// # Error Handling
    ///
    /// The method will automatically handle:
    /// - Network errors
    /// - Timeouts (if configured)
    /// - Invalid responses
    /// - Status code errors (unless configured otherwise)
    ///
    /// # Retries
    ///
    /// By default, failed requests are not automatically retried. To enable retries:
    ///
    /// ```rust,ignore
    /// use deboa::{Client, Result, request::get};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///   let mut client = Client::new();
    ///   let request = get("https://example.com").retries(3); // Retry up to 3 times
    ///   let response = client.execute(request).await?;
    ///   Ok(())
    /// }
    /// ```
    ///
    /// # Panics
    /// - If the request is invalid
    /// - If the response is a non-success status code
    ///
    /// # Performance
    ///
    /// - Uses connection pooling for better performance
    /// - Automatically reuses connections when possible
    /// - Supports HTTP/1.1, HTTP/2 and HTTP/3
    pub async fn execute<R>(&self, request: R) -> Result<DeboaResponse>
    where
        R: IntoRequest,
    {
        let request = request.into_request()?;

        let url = request
            .as_ref()
            .url();
        let mut uri = url
            .path()
            .to_string();
        if let Some(query) = url.query() {
            uri.push('?');
            uri.push_str(query);
        }

        let method = request
            .as_ref()
            .method();

        info!("Building request: {} {}", method, uri);
        let mut builder = Request::builder()
            .uri(uri)
            .method(
                method
                    .to_string()
                    .as_str(),
            );
        {
            let req_headers = builder
                .headers_mut()
                .unwrap();

            request
                .as_ref()
                .headers()
                .into_iter()
                .fold(&mut *req_headers, |acc, (key, value)| {
                    acc.insert(key, value.into());
                    acc
                });

            if let Some(deboa_cookies) = request
                .as_ref()
                .cookies()
            {
                let mut cookies = Vec::<String>::new();

                for cookie in deboa_cookies.values() {
                    cookies.push(cookie.to_string());
                }

                if let Ok(cookie_header) = HeaderValue::from_str(&cookies.join("; ")) {
                    req_headers.insert(header::COOKIE, cookie_header);
                }
            }
        }

        let request = builder.body(request.body());

        if let Err(err) = request {
            error!("Failed to send request: {}", err);
            return Err(DeboaError::Request(RequestError::Send {
                url: url.to_string(),
                message: err.to_string(),
            }));
        }

        let request = request.unwrap();

        let scheme = url.scheme();

        let host = url
            .host_str()
            .unwrap_or("localhost");

        let (port, is_secure) = if let Some(port) = url.port() {
            (port, scheme == "https" || scheme == "wss")
        } else {
            match scheme {
                "http" | "ws" => (80, false),
                "https" | "wss" => (443, true),
                _ => panic!("Unsupported scheme: {}", scheme),
            }
        };

        let config = ConnectionConfig::builder()
            .is_secure(is_secure)
            .host(host)
            .port(port)
            .protocol(
                self.protocol
                    .clone(),
            )
            .identity(
                self.identity
                    .clone(),
            )
            .certificate(
                self.certificate
                    .clone(),
            )
            .skip_cert_verification(self.skip_cert_verification)
            .client_bind_addr(self.bind_addr)
            .build();

        #[cfg(feature = "tokio-rt")]
        let mut pool = RwLockWriteGuard::map(
            self.pool
                .write()
                .await,
            |f| f,
        );
        #[cfg(feature = "smol-rt")]
        let mut pool = self
            .pool
            .write()
            .await;

        #[cfg(feature = "compio-rt")]
        let mut pool = self
            .pool
            .lock()
            .unwrap();

        let conn = pool
            .create_connection(&config)
            .await?;

        let response = conn
            .send_request(url.clone(), request)
            .await?;

        Ok(response)
    }
}