kintone 0.6.2

kintone REST API client
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
//! # Kintone HTTP Client
//!
//! This module provides the HTTP client for communicating with Kintone's REST API.
//! It handles authentication, request building, and response processing for all API calls.
//!
//! ## Key Components
//!
//! - [`KintoneClient`] - The main HTTP client for making API requests
//! - [`KintoneClientBuilder`] - Builder for configuring the client with custom options
//! - [`Auth`] - Authentication methods (API token or username/password)
//!
//! ## Authentication
//!
//! The client supports two authentication methods:
//!
//! ### API Token Authentication
//!
//! **Note**: API tokens can be generated from the Kintone app settings page.
//!
//! ```rust
//! use kintone::client::{Auth, KintoneClient};
//!
//! let client = KintoneClient::new(
//!     "https://your-domain.cybozu.com",
//!     Auth::api_token("your-api-token".to_owned())
//! );
//! ```
//!
//! ### Username/Password Authentication
//! ```rust
//! use kintone::client::{Auth, KintoneClient};
//!
//! let client = KintoneClient::new(
//!     "https://your-domain.cybozu.com",
//!     Auth::password("username".to_owned(), "password".to_owned())
//! );
//! ```
//!
//! ### Client Certificate Authentication (Mutual TLS)
//!
//! For Kintone's "Secure Access" feature:
//!
//! ```no_run
//! use kintone::client::{Auth, KintoneClientBuilder};
//!
//! let cert_pem = std::fs::read("client.crt")?;
//! let key_pem = std::fs::read("client.key")?;
//!
//! let client = KintoneClientBuilder::new(
//!     "https://your-domain.cybozu.com",
//!     Auth::api_token("your-api-token".to_owned())
//! )
//! .client_certificate_from_pem(&cert_pem, &key_pem)?
//! .build();
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Client Configuration
//!
//! For advanced configuration, use the builder pattern:
//!
//! ```rust
//! use kintone::client::{Auth, KintoneClientBuilder};
//!
//! let client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::api_token("your-api-token".to_owned())
//!     )
//!     .user_agent("MyApp/1.0")
//!     .build();
//! ```
//!
//! ## Middleware Configuration
//!
//! The client supports middleware through the builder pattern. Middleware can handle
//! cross-cutting concerns like retries, logging, and custom request/response processing.
//!
//! ### Retry Middleware
//!
//! Automatically retries failed requests with exponential backoff, particularly useful
//! for handling database lock errors (GAIA_DA02):
//!
//! ```rust
//! use std::time::Duration;
//! use kintone::client::{Auth, KintoneClientBuilder};
//! use kintone::middleware;
//!
//! let client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::api_token("your-api-token".to_owned())
//!     )
//!     .layer(middleware::RetryLayer::new()
//!         .with_max_attempts(5)
//!         .with_initial_delay(Duration::from_secs(1))
//!         .with_max_delay(Duration::from_secs(8))
//!     )
//!     .build();
//! ```
//!
//! ### Logging Middleware
//!
//! Logs detailed information about API requests and responses for debugging:
//!
//! ```rust
//! use kintone::client::{Auth, KintoneClientBuilder};
//! use kintone::middleware;
//!
//! let client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::api_token("your-api-token".to_owned())
//!     )
//!     .layer(middleware::LoggingLayer::new())
//!     .build();
//! ```
//!
//! ### Combined Middleware
//!
//! You can combine multiple middleware layers. The order in which layers are added determines
//! the execution order:
//!
//! **Important**: Layers are applied in a stack-like manner. The first layer added becomes the
//! outermost layer, and subsequent layers are nested inside. For requests, the execution flows
//! from the outermost layer to the innermost, and for responses, it flows back in reverse order.
//!
//! ```rust
//! use std::time::Duration;
//! use kintone::client::{Auth, KintoneClientBuilder};
//! use kintone::middleware;
//!
//! let client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::password("username".to_owned(), "password".to_owned())
//!     )
//!     .layer(middleware::RetryLayer::new()
//!         .with_max_attempts(5)
//!         .with_initial_delay(Duration::from_secs(1))
//!         .with_max_delay(Duration::from_secs(8))
//!     )
//!     .layer(middleware::LoggingLayer::new())  // Layer B (inner) - logs actual requests
//!     .build();
//!
//! // Execution flow:
//! // Request:  RetryLayer -> LoggingLayer -> HTTP Request
//! // Response: HTTP Response -> LoggingLayer -> RetryLayer
//! //
//! // This means:
//! // 1. RetryLayer receives the original request
//! // 2. LoggingLayer logs each actual request attempt (including retries)
//! // 3. HTTP request is sent
//! // 4. LoggingLayer logs each response (including retry attempts)
//! // 5. RetryLayer decides whether to retry or return the final response
//! //
//! // This order ensures that all retry attempts are logged, giving you
//! // complete visibility into what requests were actually sent.
//! ```
//!
//! ## Guest Space Support
//!
//! The client supports guest spaces by specifying a guest space ID during client creation.
//!
//! Each guest space requires its own `KintoneClient` instance. You cannot
//! use a single client to access multiple guest spaces or mix guest space and regular space operations.
//!
//! ### Creating a Client for Guest Space
//! ```rust
//! use kintone::client::{Auth, KintoneClientBuilder};
//!
//! // Client for guest space ID 123
//! let guest_client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::api_token("your-api-token".to_owned())
//!     )
//!     .guest_space_id(123)
//!     .build();
//!
//! // If you need to access a different guest space (ID 456), create another client
//! let another_guest_client = KintoneClientBuilder::new(
//!         "https://your-domain.cybozu.com",
//!         Auth::api_token("your-api-token".to_owned())
//!     )
//!     .guest_space_id(456)
//!     .build();
//! ```

use std::fmt::Debug;
use std::io::Cursor;
use std::io::Read;

use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use rand::RngCore as _;
use serde::Serialize;
use serde::de::DeserializeOwned;
use ureq::tls::{Certificate, ClientCert, PrivateKey, TlsConfig};

use crate::error::ApiError;
use crate::middleware;

/// The main HTTP client for communicating with Kintone's REST API.
///
/// This client handles authentication, request building, and response processing
/// for all API calls. It supports both API token and username/password authentication,
/// as well as guest spaces.
///
/// The client is designed to be reused across multiple API calls and is thread-safe.
/// For advanced configuration like middleware support, use [`KintoneClientBuilder`].
///
/// # Examples
///
/// ```rust
/// use kintone::client::{Auth, KintoneClient};
///
/// // Simple client creation
/// let client = KintoneClient::new(
///     "https://your-domain.cybozu.com",
///     Auth::api_token("your-api-token".to_owned())
/// );
/// ```
pub struct KintoneClient {
    base_url: url::Url,
    auth: Auth,
    guest_space_id: Option<u64>,
    handler: Box<dyn middleware::Handler>,
}

impl KintoneClient {
    /// Creates a new Kintone client with the specified base URL and authentication.
    ///
    /// This is a convenience method that creates a client with default settings.
    /// For advanced configuration (middleware, guest spaces, custom user agent, etc.),
    /// use [`KintoneClientBuilder`] instead.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of your Kintone environment (e.g., "https://your-domain.cybozu.com")
    /// * `auth` - Authentication configuration (API token or username/password)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::{Auth, KintoneClient};
    ///
    /// // Using API token authentication
    /// let client = KintoneClient::new(
    ///     "https://your-domain.cybozu.com",
    ///     Auth::api_token("your-api-token".to_owned())
    /// );
    ///
    /// // Using username/password authentication
    /// let client = KintoneClient::new(
    ///     "https://your-domain.cybozu.com",
    ///     Auth::password("username".to_owned(), "password".to_owned())
    /// );
    /// ```
    pub fn new(base_url: &str, auth: Auth) -> Self {
        KintoneClientBuilder::new(base_url, auth).build()
    }

    pub(crate) fn run(
        &self,
        req: http::Request<middleware::RequestBody>,
    ) -> Result<http::Response<middleware::ResponseBody>, ApiError> {
        self.handler.handle(req)
    }
}

/// Internal HTTP request handler that implements the actual HTTP communication.
///
/// This is an internal implementation detail and should not be used directly.
/// Use [`KintoneClient`] or [`KintoneClientBuilder`] instead.
pub struct RequestHandler {
    http_client: ureq::Agent,
}

impl middleware::Handler for RequestHandler {
    fn handle(
        &self,
        req: http::Request<middleware::RequestBody>,
    ) -> Result<http::Response<middleware::ResponseBody>, ApiError> {
        let req = req.map(|body| body.into_ureq_body());
        let resp = self.http_client.run(req)?;
        if resp.status().as_u16() >= 400 {
            return Err(ApiError::from(resp));
        }
        let (parts, body) = resp.into_parts();
        let body = middleware::ResponseBody::from_ureq_body(body);
        Ok(http::Response::from_parts(parts, body))
    }
}

/// Builder for configuring and creating [`KintoneClient`] instances.
///
/// This builder provides a fluent API for configuring various aspects of the Kintone client,
/// including middleware, user agent, and guest space settings. The builder uses a type-safe
/// approach to ensure that middleware layers are properly configured.
///
/// # Type Parameters
///
/// * `L` - The middleware layer type. This is used to ensure type safety when building
///   the middleware stack.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
/// use kintone::client::{Auth, KintoneClientBuilder};
/// use kintone::middleware;
///
/// let client = KintoneClientBuilder::new(
///         "https://your-domain.cybozu.com",
///         Auth::api_token("your-api-token".to_owned())
///     )
///     .user_agent("MyApp/1.0")
///     .guest_space_id(123)
///     .layer(middleware::RetryLayer::new()
///         .with_max_attempts(5)
///         .with_initial_delay(Duration::from_secs(1))
///         .with_max_delay(Duration::from_secs(8))
///     )
///     .layer(middleware::LoggingLayer::new())
///     .build();
/// ```
pub struct KintoneClientBuilder<L> {
    base_url: url::Url,
    auth: Auth,
    user_agent: Option<String>,
    guest_space_id: Option<u64>,
    client_cert: Option<ClientCert>,
    layer: L,
}

impl KintoneClientBuilder<middleware::NoLayer> {
    /// Creates a new Kintone client builder with the specified base URL and authentication.
    ///
    /// This is the starting point for building a customized Kintone client. The builder
    /// allows you to configure various aspects like middleware, guest spaces, user agent,
    /// and client certificates before creating the final client.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of your Kintone environment (e.g., "https://your-domain.cybozu.com")
    /// * `auth` - Authentication configuration (API token or username/password)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::{Auth, KintoneClientBuilder};
    ///
    /// let builder = KintoneClientBuilder::new(
    ///     "https://your-domain.cybozu.com",
    ///     Auth::api_token("your-api-token".to_owned())
    /// );
    ///
    /// // Configure additional options and build the client
    /// let client = builder
    ///     .user_agent("MyApp/1.0")
    ///     .guest_space_id(123)
    ///     .build();
    /// ```
    pub fn new(base_url: &str, auth: Auth) -> Self {
        let base_url = url::Url::parse(base_url).unwrap();
        Self {
            base_url,
            auth,
            user_agent: None,
            guest_space_id: None,
            client_cert: None,
            layer: middleware::NoLayer,
        }
    }
}

impl<L> KintoneClientBuilder<L> {
    /// Adds a middleware layer to the client configuration.
    ///
    /// Middleware layers provide a way to intercept and modify requests and responses.
    /// Common use cases include retry logic, logging, authentication, and error handling.
    ///
    /// Layers are applied in a stack-like manner. The first layer added becomes the
    /// outermost layer, and subsequent layers are nested inside. For requests, execution
    /// flows from the outermost layer to the innermost, and for responses, it flows back
    /// in reverse order.
    ///
    /// # Type Parameters
    ///
    /// * `L2` - The type of the middleware layer to add
    ///
    /// # Arguments
    ///
    /// * `new_layer` - The middleware layer instance to add
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use kintone::client::{Auth, KintoneClientBuilder};
    /// use kintone::middleware;
    ///
    /// let client = KintoneClientBuilder::new(
    ///         "https://your-domain.cybozu.com",
    ///         Auth::api_token("your-api-token".to_owned())
    ///     )
    ///     .layer(middleware::RetryLayer::new()
    ///         .with_max_attempts(5)
    ///         .with_initial_delay(Duration::from_secs(1))
    ///         .with_max_delay(Duration::from_secs(8))
    ///     )
    ///     .layer(middleware::LoggingLayer::new())
    ///     .build();
    /// ```
    pub fn layer<L2>(self, new_layer: L2) -> KintoneClientBuilder<middleware::Stack<L, L2>> {
        let layer_stack = middleware::Stack::new(self.layer, new_layer);
        KintoneClientBuilder {
            base_url: self.base_url,
            auth: self.auth,
            user_agent: self.user_agent,
            guest_space_id: self.guest_space_id,
            client_cert: self.client_cert,
            layer: layer_stack,
        }
    }

    /// Configures the client to operate within a specific guest space.
    ///
    /// Guest spaces in Kintone provide isolated environments within your domain.
    /// When a guest space ID is specified, all API requests will be made within
    /// that guest space context.
    ///
    /// **Important**: Each guest space requires its own client instance. You cannot
    /// use a single client to access multiple guest spaces or mix guest space and
    /// regular space operations.
    ///
    /// # Arguments
    ///
    /// * `guest_space_id` - The numeric ID of the guest space
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::{Auth, KintoneClientBuilder};
    ///
    /// // Client for guest space ID 123
    /// let guest_client = KintoneClientBuilder::new(
    ///         "https://your-domain.cybozu.com",
    ///         Auth::api_token("your-api-token".to_owned())
    ///     )
    ///     .guest_space_id(123)
    ///     .build();
    /// ```
    pub fn guest_space_id(mut self, guest_space_id: u64) -> Self {
        self.guest_space_id = Some(guest_space_id);
        self
    }

    /// Sets a custom User-Agent header for HTTP requests.
    ///
    /// The User-Agent header identifies your application to the Kintone server.
    /// This can be useful for debugging, analytics, or server-side logging.
    /// If not specified, defaults to "kintone-rs".
    ///
    /// # Arguments
    ///
    /// * `user_agent` - The User-Agent string to use for requests
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::{Auth, KintoneClientBuilder};
    ///
    /// let client = KintoneClientBuilder::new(
    ///         "https://your-domain.cybozu.com",
    ///         Auth::api_token("your-api-token".to_owned())
    ///     )
    ///     .user_agent("MyApp/1.0")
    ///     .build();
    /// ```
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Sets a client certificate for mutual TLS authentication.
    ///
    /// This method configures the client to use a client certificate for authentication,
    /// which is required when using cybozu.com's "Secure Access" feature.
    /// Secure Access is an enterprise security feature that requires mutual TLS (mTLS)
    /// authentication using client certificates.
    ///
    /// The certificate and private key must be provided in PEM format.
    ///
    /// # Important: Secure Access Base URL
    ///
    /// When using client certificate authentication with Kintone Secure Access, your base URL
    /// **must** include the `.s` subdomain. For example:
    /// - Correct: `https://your-domain.s.cybozu.com`
    /// - Incorrect: `https://your-domain.cybozu.com`
    ///
    /// The `.s` subdomain is required for Secure Access endpoints that support client certificates.
    ///
    /// # Arguments
    ///
    /// * `cert_pem` - The client certificate in PEM format (as bytes)
    /// * `key_pem` - The private key corresponding to the certificate in PEM format (as bytes)
    ///
    /// # Converting from PFX format
    ///
    /// Secure Access certificates are typically downloaded in PFX (PKCS#12) format.
    /// You can convert them to PEM format using OpenSSL commands:
    ///
    /// ```bash
    /// openssl pkcs12 -in input.pfx -nokeys -out client-cert.pem
    /// openssl pkcs12 -in input.pfx -nocerts -out client-key.pem -nodes
    /// ```
    ///
    /// The `-nodes` flag ensures the private key is not encrypted with a passphrase.
    /// After conversion, you can load these PEM files using the example below.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use kintone::client::{Auth, KintoneClientBuilder};
    ///
    /// // Load certificate and key from PEM files
    /// let cert_pem = std::fs::read("client-cert.pem")?;
    /// let key_pem = std::fs::read("client-key.pem")?;
    ///
    /// let client = KintoneClientBuilder::new(
    ///         "https://your-domain.s.cybozu.com", // Don't forget ".s"
    ///         Auth::api_token("your-api-token".to_owned())
    ///     )
    ///     .client_certificate_from_pem(&cert_pem, &key_pem)?
    ///     .build();
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn client_certificate_from_pem(
        mut self,
        cert_pem: &[u8],
        key_pem: &[u8],
    ) -> Result<Self, std::io::Error> {
        let cert = Certificate::from_pem(cert_pem).map_err(|e| e.into_io())?;
        let key = PrivateKey::from_pem(key_pem).map_err(|e| e.into_io())?;
        self.client_cert = Some(ClientCert::new_with_certs(&[cert], key));
        Ok(self)
    }
}

impl<L> KintoneClientBuilder<L>
where
    L: middleware::Layer<RequestHandler>,
{
    /// Builds the final [`KintoneClient`] instance with all configured options.
    ///
    /// This method consumes the builder and creates a ready-to-use Kintone client
    /// with all the specified configuration including middleware layers, authentication,
    /// guest space settings, and client certificates.
    ///
    /// # Returns
    ///
    /// A configured [`KintoneClient`] instance ready for making API requests.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use kintone::client::{Auth, KintoneClientBuilder};
    /// use kintone::middleware;
    ///
    /// let client = KintoneClientBuilder::new(
    ///         "https://your-domain.cybozu.com",
    ///         Auth::api_token("your-api-token".to_owned())
    ///     )
    ///     .user_agent("MyApp/1.0")
    ///     .layer(middleware::LoggingLayer::new())
    ///     .build();
    /// ```
    pub fn build(self) -> KintoneClient {
        let user_agent = self.user_agent.unwrap_or_else(|| "kintone-rs".to_owned());
        let http_client: ureq::Agent = ureq::Agent::config_builder()
            .user_agent(&user_agent)
            .http_status_as_error(false)
            .tls_config(TlsConfig::builder().client_cert(self.client_cert).build())
            .build()
            .into();

        let handler = self.layer.layer(RequestHandler { http_client });

        KintoneClient {
            base_url: self.base_url,
            auth: self.auth,
            guest_space_id: self.guest_space_id,
            handler: Box::new(handler),
        }
    }
}

/// Authentication configuration for Kintone API access.
///
/// Kintone supports two primary authentication methods:
/// - API Token authentication
/// - Username/Password authentication
///
/// **Note**: If your domain requires Basic authentication, use [`crate::middleware::BasicAuthLayer`]
/// middleware in addition to your Kintone authentication. BasicAuthLayer adds the necessary
/// `Authorization: Basic` headers for domain-level authentication, while the Auth configuration handles
/// Kintone's own authentication mechanism.
///
/// # Examples
///
/// ```rust
/// use kintone::client::Auth;
///
/// // API token authentication
/// let auth = Auth::api_token("your-api-token".to_owned());
///
/// // Multiple API tokens (for accessing multiple apps)
/// let auth = Auth::api_tokens(vec![
///     "token1".to_owned(),
///     "token2".to_owned(),
/// ]);
///
/// // Username/password authentication
/// let auth = Auth::password("username".to_owned(), "password".to_owned());
/// ```
#[derive(Clone)]
pub enum Auth {
    Password { username: String, password: String },
    ApiToken { tokens: Vec<String> },
}

impl Auth {
    /// Creates password-based authentication configuration.
    ///
    /// This authentication method uses a Kintone username and password.
    ///
    /// # Arguments
    ///
    /// * `username` - The Kintone username
    /// * `password` - The user's password
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::Auth;
    ///
    /// let auth = Auth::password("john.doe".to_owned(), "secret123".to_owned());
    /// ```
    pub fn password(username: String, password: String) -> Self {
        Self::Password { username, password }
    }

    /// Creates API token-based authentication configuration for a single token.
    ///
    /// API tokens provide secure, app-specific authentication without requiring
    /// user passwords. Tokens can be generated from the Kintone app settings page.
    ///
    /// # Arguments
    ///
    /// * `token` - The API token string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::Auth;
    ///
    /// let auth = Auth::api_token("your-api-token".to_owned());
    /// ```
    pub fn api_token(token: String) -> Self {
        Self::ApiToken {
            tokens: vec![token],
        }
    }

    /// Creates API token-based authentication configuration for multiple tokens.
    ///
    /// When your application needs to access multiple Kintone apps that have
    /// different API tokens, you can specify multiple tokens. This is useful
    /// when working with apps that have separate access controls.
    ///
    /// # Arguments
    ///
    /// * `tokens` - A vector of API token strings
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::client::Auth;
    ///
    /// let auth = Auth::api_tokens(vec![
    ///     "token-for-app1".to_owned(),
    ///     "token-for-app2".to_owned(),
    /// ]);
    /// ```
    pub fn api_tokens(tokens: Vec<String>) -> Self {
        Self::ApiToken { tokens }
    }
}

impl Debug for Auth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Auth::Password { username, .. } => f
                .debug_struct("Password")
                .field("username", username)
                .field("password", &"<hidden>")
                .finish(),
            Auth::ApiToken { .. } => {
                f.debug_struct("ApiToken").field("tokens", &"<hidden>").finish()
            }
        }
    }
}

pub(crate) struct RequestBuilder {
    method: http::Method,
    api_path: String,               // DO NOT include "/k" prefix
    headers: Vec<(String, String)>, // keys and values are NOT encoded
    query: Vec<(String, String)>,   // keys and values are NOT encoded
}

impl RequestBuilder {
    pub fn new(method: http::Method, api_path: impl Into<String>) -> Self {
        Self {
            method,
            api_path: api_path.into(),
            headers: Vec::new(),
            query: Vec::new(),
        }
    }

    pub fn query<V: ToString>(mut self, key: &str, value: V) -> Self {
        self.query.push((key.to_owned(), value.to_string()));
        self
    }

    pub fn query_array<V: ToString>(mut self, key: &str, values: &[V]) -> Self {
        for (i, v) in values.iter().enumerate() {
            let name = format!("{key}[{i}]");
            self.query.push((name, v.to_string()));
        }
        self
    }

    pub fn call<Resp: DeserializeOwned>(self, client: &KintoneClient) -> Result<Resp, ApiError> {
        let req = make_request(client, self.method, &self.api_path, self.headers, self.query)?;
        let resp = client.run(req)?;
        resp.into_body().read_json()
    }

    pub fn send<Body: Serialize, Resp: DeserializeOwned>(
        mut self,
        client: &KintoneClient,
        body: Body,
    ) -> Result<Resp, ApiError> {
        let body = middleware::RequestBody::from_bytes(serde_json::to_vec_pretty(&body)?);
        self.headers.push(("content-type".to_owned(), "application/json".to_owned()));
        let req = make_request(client, self.method, &self.api_path, self.headers, self.query)?
            .map(|_| body);
        let resp = client.run(req)?;
        resp.into_body().read_json()
    }
}

/// Internal builder for file upload requests to the Kintone API.
///
/// This builder handles the multipart/form-data encoding required for file uploads
/// to Kintone. It automatically generates proper boundaries and formats the request
/// according to the multipart specification.
///
/// This is an internal implementation detail and should not be used directly.
/// Use the [`crate::v1::file::upload`] function instead.
///
/// # Examples
///
/// This is typically used internally like:
/// ```ignore
/// let upload = UploadRequest::new(
///     http::Method::POST,
///     "/v1/file.json",
///     "file".to_owned(),
///     "document.pdf".to_owned()
/// );
/// let response = upload.send(&client, file_content)?;
/// ```
pub(crate) struct UploadRequest {
    method: http::Method,
    api_path: String, // DO NOT include "/k" prefix
    name: String,
    filename: String,
}

impl UploadRequest {
    pub fn new(
        method: http::Method,
        api_path: impl Into<String>,
        name: String,
        filename: String,
    ) -> Self {
        Self {
            method,
            api_path: api_path.into(),
            name,
            filename,
        }
    }

    const CONTROLS_AND_QUOTES: &percent_encoding::AsciiSet =
        &percent_encoding::CONTROLS.add(b'\'').add(b'"').add(b'\\');

    pub fn send<Resp: DeserializeOwned>(
        self,
        client: &KintoneClient,
        content_type: Option<String>,
        content: impl Read + Send + Sync + 'static,
    ) -> Result<Resp, ApiError> {
        let mut rng = rand::rng();
        let boundary = format!("{:x}{:x}", rng.next_u64(), rng.next_u64());

        let outer_content_type = format!("multipart/form-data; boundary={boundary}");
        let headers = [("content-type".to_owned(), outer_content_type)];

        let inner_content_type_header = match content_type {
            Some(ref ct) => format!("Content-Type: {ct}\r\n"),
            None => String::new(),
        };

        let header = format!(
            "--{boundary}\r\n\
             Content-Disposition: form-data; name=\"{}\"; filename*=utf8''{}\r\n\
             {inner_content_type_header}\
             \r\n",
            percent_encoding::utf8_percent_encode(&self.name, Self::CONTROLS_AND_QUOTES),
            percent_encoding::utf8_percent_encode(
                &self.filename,
                percent_encoding::NON_ALPHANUMERIC
            ),
        );
        let footer = format!("\r\n--{boundary}--\r\n");

        let header_reader = Cursor::new(header.into_bytes());
        let footer_reader = Cursor::new(footer.into_bytes());
        let body_reader = header_reader.chain(content).chain(footer_reader);
        let body = middleware::RequestBody::from_reader(body_reader);

        let req = make_request(client, self.method, &self.api_path, headers, vec![])?.map(|_| body);

        let resp = client.run(req)?;
        resp.into_body().read_json()
    }
}

/// Internal builder for file download requests from the Kintone API.
///
/// This builder handles the download of files from Kintone, including proper
/// content-type detection and streaming of file content. It supports downloading
/// files by their file key.
///
/// This is an internal implementation detail and should not be used directly.
/// Use the [`crate::v1::file::download`] function instead.
pub(crate) struct DownloadRequest {
    method: http::Method,
    api_path: String,             // DO NOT include "/k" prefix
    query: Vec<(String, String)>, // keys and values are NOT encoded
}

/// Response from a file download operation.
///
/// Contains the downloaded file's content as a readable stream and its MIME type.
/// The content is provided as a `Read` trait object to allow for efficient streaming
/// of large files without loading them entirely into memory.
///
/// # Examples
///
/// ```ignore
/// let response = download_request.send(&client)?;
/// println!("Downloaded file type: {}", response.mime_type);
///
/// // Stream the content to a file
/// let mut file = std::fs::File::create("downloaded_file")?;
/// std::io::copy(&mut response.content, &mut file)?;
/// ```
pub(crate) struct DownloadResponse {
    pub mime_type: Option<mime::Mime>,
    pub content: Box<dyn Read + Send + Sync + 'static>,
}

impl DownloadRequest {
    pub fn new(method: http::Method, api_path: impl Into<String>) -> Self {
        Self {
            method,
            api_path: api_path.into(),
            query: Vec::new(),
        }
    }

    pub fn query<V: ToString>(mut self, key: &str, value: V) -> Self {
        self.query.push((key.to_owned(), value.to_string()));
        self
    }

    fn get_content_type<B>(resp: &http::Response<B>) -> Option<mime::Mime> {
        let content_type = resp.headers().get(http::header::CONTENT_TYPE)?;
        let content_type = content_type.to_str().ok()?;
        content_type.parse().ok()
    }

    pub fn send(self, client: &KintoneClient) -> Result<DownloadResponse, ApiError> {
        let req = make_request(client, self.method, &self.api_path, vec![], self.query)?;
        let resp = client.run(req)?;
        let mime_type = Self::get_content_type(&resp);
        let content_reader = Box::new(resp.into_body().into_reader());
        Ok(DownloadResponse {
            mime_type,
            content: content_reader,
        })
    }
}

fn make_request(
    client: &KintoneClient,
    method: http::Method,
    api_path: &str,
    headers: impl IntoIterator<Item = (String, String)>,
    query: impl IntoIterator<Item = (String, String)>,
) -> Result<http::Request<middleware::RequestBody>, http::Error> {
    // Add headers for auth
    let auth_headers = match client.auth {
        Auth::Password {
            ref username,
            ref password,
        } => {
            let body = format!("{username}:{password}");
            let header_value = BASE64.encode(body);
            [("x-cybozu-authorization".to_owned(), header_value)]
        }
        Auth::ApiToken { ref tokens } => [("x-cybozu-api-token".to_owned(), tokens.join(","))],
    };

    // Construct URL
    let mut u = client.base_url.clone();
    let mut path = if let Some(guest_space_id) = client.guest_space_id {
        format!("/k/guest/{guest_space_id}")
    } else {
        "/k".to_owned()
    };
    path += api_path;
    u.set_path(&path);
    for (key, value) in query {
        u.query_pairs_mut().append_pair(&key, &value);
    }

    let mut req = http::Request::builder().method(method).uri(u.as_str());
    let all_headers = headers.into_iter().chain(auth_headers);
    for (key, value) in all_headers {
        req = req.header(&key, &value);
    }
    req.body(middleware::RequestBody::void())
}