crabrave 0.4.0

A Tumblr API client for Rust.
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
//! # Crabrave
//!
//! An ergonomic Rust HTTP client for the Tumblr API.
//!
//! Inspired by [Octocrab](https://github.com/XAMPPRocky/octocrab), Crabrave provides
//! a type-safe, async interface for interacting with Tumblr's REST API.
//!
//! ## Quick Start
//!
//! ### Using Existing Credentials
//!
//! ```
//! use crabrave::Crabrave;
//!
//! // Build a client with OAuth2 credentials
//! let crab = Crabrave::builder()
//!     .consumer_key("your_consumer_key")
//!     .consumer_secret("your_consumer_secret")
//!     .access_token("your_access_token")
//!     .build()?;
//!
//! // Use the client (requires async runtime)
//! // let blog_info = crab.blogs("staff").info().await?;
//! # Ok::<(), crabrave::CrabError>(())
//! ```
//!
//! ### OAuth2 Flow (Getting Tokens)
//!
//! ```no_run
//! use crabrave::oauth::OAuth2Config;
//! use crabrave::Crabrave;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Create OAuth2 config
//! let config = OAuth2Config::new(
//!     "your_consumer_key",
//!     "your_consumer_secret",
//!     "http://localhost:8080/callback"
//! )?;
//!
//! // 2. Generate authorization URL
//! let (auth_url, csrf_token) = config.authorize_url();
//! println!("Visit: {}", auth_url);
//! // Direct user to auth_url, they'll be redirected back with a code
//!
//! // 3. Exchange authorization code for token
//! let code = "code_from_callback";
//! let token = config.exchange_code(code).await?;
//!
//! // 4. Create client with the token
//! let crab = Crabrave::builder()
//!     .consumer_key("your_consumer_key")
//!     .consumer_secret("your_consumer_secret")
//!     .access_token(&token.access_token)
//!     .build()?;
//!
//! // 5. Use the client
//! let blog_info = crab.blogs("staff").info().await?;
//! # Ok(())
//! # }
//! ```

mod error;
pub mod handlers;
pub mod media;
pub mod models;
pub mod npf;
pub mod oauth;
mod response;

pub use error::{CrabError, CrabResult};
pub use handlers::{Blogs, Communities, Tagged, Users};
pub use models::{Blog, BlogIdentifier, Page, User};
pub use response::{ApiResponse, EmptyResponse, Meta};

use base64::Engine;
use hmac::{Hmac, Mac};
use rand::Rng;
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
use serde::{Deserialize, Deserializer};
use sha1::Sha1;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::handlers::blog::{AvatarResponse, AvatarResponseUrl};

/// Base URL for the Tumblr API v2
pub const BASE_API_URL: &str = "https://api.tumblr.com/v2";

/// OAuth2 authorization endpoint
pub const OAUTH_AUTHORIZE_URL: &str = "https://www.tumblr.com/oauth2/authorize";

/// OAuth2 token endpoint
pub const OAUTH_TOKEN_URL: &str = "https://api.tumblr.com/v2/oauth2/token";

/// Default User-Agent header value
const DEFAULT_USER_AGENT: &str = concat!(
    "crabrave/",
    env!("CARGO_PKG_VERSION"),
    " (Rust HTTP Client for Tumblr)"
);

/// Authentication credentials for the Tumblr API
#[derive(Clone)]
enum Auth {
    /// OAuth2 authentication with access token
    OAuth2 {
        #[allow(dead_code)] // Stored for potential token refresh, but not used in requests
        consumer_key: String,
        #[allow(dead_code)] // Stored for potential token refresh, but not used in requests
        consumer_secret: String,
        access_token: String,
    },
    /// OAuth1 authentication (legacy)
    OAuth1 {
        consumer_key: String,
        consumer_secret: String,
        access_token: String,
        access_token_secret: String,
    },
    /// API key only (read-only access)
    ApiKey { consumer_key: String },
}

/// The main client for interacting with the Tumblr API
#[derive(Clone)]
pub struct Crabrave {
    client: reqwest::Client,
    base_url: String,
    auth: Arc<Auth>,
}

impl Crabrave {
    /// Creates a new builder for constructing a `Crabrave` client
    ///
    /// # Example
    ///
    /// ```no_run
    /// use crabrave::Crabrave;
    ///
    /// let crab = Crabrave::builder()
    ///     .consumer_key("key")
    ///     .consumer_secret("secret")
    ///     .access_token("token")
    ///     .build()?;
    /// # Ok::<(), crabrave::CrabError>(())
    /// ```
    pub fn builder() -> CrabraveBuilder {
        CrabraveBuilder::new()
    }

    /// Gets the base URL for API requests
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Gets a reference to the underlying reqwest client
    pub fn client(&self) -> &reqwest::Client {
        &self.client
    }

    /// Creates an API accessor for blog-related operations
    ///
    /// # Arguments
    ///
    /// * `identifier` - Blog identifier (name, hostname, or UUID)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use crabrave::Crabrave;
    /// # async fn example() -> Result<(), crabrave::CrabError> {
    /// # let crab = Crabrave::builder().consumer_key("key").build()?;
    /// // Using blog name
    /// let info = crab.blogs("staff").info().await?;
    ///
    /// // Using hostname
    /// let info = crab.blogs("staff.tumblr.com").info().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn blogs(&self, identifier: impl Into<BlogIdentifier>) -> Blogs {
        Blogs::new(self.clone(), identifier.into())
    }

    /// Creates an API accessor for user-related operations
    ///
    /// This provides access to the authenticated user's dashboard,
    /// likes, following list, and other user-specific operations.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use crabrave::Crabrave;
    /// # async fn example() -> Result<(), crabrave::CrabError> {
    /// # let crab = Crabrave::builder()
    /// #     .consumer_key("key")
    /// #     .consumer_secret("secret")
    /// #     .access_token("token")
    /// #     .build()?;
    /// // Get user info
    /// let info = crab.users().info().await?;
    ///
    /// // Get dashboard posts
    /// let posts = crab.users().dashboard().limit(20).send().await?;
    ///
    /// // Follow a blog
    /// crab.users().follow("staff").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn users(&self) -> Users {
        Users::new(self.clone())
    }

    /// Creates an API accessor for searching posts by tag
    ///
    /// This provides access to public posts across the platform that have been
    /// tagged with a specific tag.
    ///
    /// # Arguments
    ///
    /// * `tag` - The tag to search for
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use crabrave::Crabrave;
    /// # async fn example() -> Result<(), crabrave::CrabError> {
    /// # let crab = Crabrave::builder().consumer_key("key").build()?;
    /// // Search for posts tagged with "photography"
    /// let posts = crab.tagged("photography").limit(20).send().await?;
    ///
    /// for post in posts.posts {
    ///     println!("Post from {}: {}", post.blog_name, post.id);
    /// }
    ///
    /// // Search with timestamp filter
    /// let older_posts = crab.tagged("art").before(1234567890).send().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn tagged(&self, tag: impl Into<String>) -> handlers::Tagged {
        handlers::Tagged::new(self.clone(), tag.into())
    }

    /// Creates an API accessor for community operations
    ///
    /// This provides access to community timelines, membership management,
    /// and member lists.
    ///
    /// # Arguments
    ///
    /// * `handle` - Community handle/identifier
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use crabrave::Crabrave;
    /// # async fn example() -> Result<(), crabrave::CrabError> {
    /// # let crab = Crabrave::builder()
    /// #     .consumer_key("key")
    /// #     .consumer_secret("secret")
    /// #     .access_token("token")
    /// #     .build()?;
    /// // Get community timeline
    /// let timeline = crab.communities("rust-community")
    ///     .timeline()
    ///     .limit(20)
    ///     .send()
    ///     .await?;
    ///
    /// // Join a community
    /// crab.communities("rust-community").join().await?;
    ///
    /// // Get community members
    /// let members = crab.communities("rust-community")
    ///     .members()
    ///     .limit(20)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn communities(&self, handle: impl Into<String>) -> Communities {
        Communities::new(self.clone(), handle.into())
    }

    /// Constructs a full URL for an API endpoint
    ///
    /// # Arguments
    ///
    /// * `path` - The API endpoint path (e.g., "/blog/staff/info")
    pub(crate) fn url(&self, path: &str) -> String {
        let path = path.trim_start_matches('/');
        format!("{}/{}", self.base_url, path)
    }

    /// Generates an OAuth1 signature for a request
    fn generate_oauth1_signature(
        &self,
        method: &str,
        url: &str,
        consumer_key: &str,
        consumer_secret: &str,
        access_token: &str,
        access_token_secret: &str,
    ) -> String {
        // Generate timestamp and nonce
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs().to_string())
            .unwrap_or_else(|_| "0".to_string());

        // Generate cryptographically random nonce (32 alphanumeric characters)
        let nonce: String = rand::rng()
            .sample_iter(&rand::distr::Alphanumeric)
            .take(32)
            .map(char::from)
            .collect();

        // Collect OAuth parameters (using String keys and values to avoid lifetime issues)
        let mut params: BTreeMap<String, String> = BTreeMap::new();
        params.insert("oauth_consumer_key".to_string(), consumer_key.to_string());
        params.insert("oauth_nonce".to_string(), nonce.clone());
        params.insert(
            "oauth_signature_method".to_string(),
            "HMAC-SHA1".to_string(),
        );
        params.insert("oauth_timestamp".to_string(), timestamp.clone());
        params.insert("oauth_token".to_string(), access_token.to_string());
        params.insert("oauth_version".to_string(), "1.0".to_string());

        // Parse URL to extract query parameters
        if let Ok(parsed_url) = url::Url::parse(url) {
            for (key, value) in parsed_url.query_pairs() {
                params.insert(key.to_string(), value.to_string());
            }
        }

        // Build parameter string
        let param_string: String = params
            .iter()
            .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
            .collect::<Vec<_>>()
            .join("&");

        // Build signature base string
        let base_url = url.split('?').next().unwrap_or(url);
        let signature_base = format!(
            "{}&{}&{}",
            urlencoding::encode(method),
            urlencoding::encode(base_url),
            urlencoding::encode(&param_string)
        );

        // Build signing key
        let signing_key = format!(
            "{}&{}",
            urlencoding::encode(consumer_secret),
            urlencoding::encode(access_token_secret)
        );

        // Generate HMAC-SHA1 signature
        type HmacSha1 = Hmac<Sha1>;
        // HMAC-SHA1 accepts keys of any size per specification
        #[allow(clippy::expect_used)]
        let mut mac = HmacSha1::new_from_slice(signing_key.as_bytes())
            .expect("HMAC-SHA1 accepts keys of any size");
        mac.update(signature_base.as_bytes());
        let result = mac.finalize();
        let signature = base64::engine::general_purpose::STANDARD.encode(result.into_bytes());

        // Build Authorization header
        format!(
            r#"OAuth oauth_consumer_key="{}", oauth_nonce="{}", oauth_signature="{}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="{}", oauth_token="{}", oauth_version="1.0""#,
            urlencoding::encode(consumer_key),
            urlencoding::encode(&nonce),
            urlencoding::encode(&signature),
            timestamp,
            urlencoding::encode(access_token)
        )
    }

    /// Applies authentication to a request builder based on the auth type
    fn apply_auth(
        &self,
        mut request: reqwest::RequestBuilder,
        method: &str,
        url: &str,
    ) -> reqwest::RequestBuilder {
        match self.auth.as_ref() {
            Auth::OAuth2 { access_token, .. } => {
                // Add Bearer token to Authorization header
                request = request.header(
                    reqwest::header::AUTHORIZATION,
                    format!("Bearer {}", access_token),
                );
            }
            Auth::OAuth1 {
                consumer_key,
                consumer_secret,
                access_token,
                access_token_secret,
            } => {
                // Generate OAuth1 signature and add Authorization header
                let auth_header = self.generate_oauth1_signature(
                    method,
                    url,
                    consumer_key,
                    consumer_secret,
                    access_token,
                    access_token_secret,
                );
                request = request.header(reqwest::header::AUTHORIZATION, auth_header);
            }
            Auth::ApiKey { consumer_key } => {
                // Add API key as query parameter
                request = request.query(&[("api_key", consumer_key)]);
            }
        }
        request
    }

    /// Checks if the response indicates rate limiting and returns an error if so.
    fn check_rate_limit(response: &reqwest::Response) -> CrabResult<()> {
        if response.status().as_u16() == 429 {
            let retry_after = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse().ok());
            return Err(CrabError::RateLimit { retry_after });
        }
        Ok(())
    }

    /// Makes a GET request to the API
    ///
    /// This is an internal helper method used by handlers.
    #[allow(dead_code)]
    pub(crate) async fn get<T>(&self, path: &str) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.url(path);
        let request = self.client.get(&url);
        let request = self.apply_auth(request, "GET", &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;

        response::parse_response_bytes(&bytes)
    }

    /// Makes a GET request with query parameters to the API
    ///
    /// This is an internal helper method used by handlers.
    /// The query parameter is serialized using serde, allowing for type-safe
    /// query parameters with automatic URL encoding.
    #[allow(dead_code)]
    pub(crate) async fn get_with_query<T, Q>(&self, path: &str, query: &Q) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        Q: serde::Serialize,
    {
        // Serialize query params to build the full URL for OAuth1 signature
        let query_string = serde_urlencoded::to_string(query).map_err(|e| {
            CrabError::InvalidResponse(format!("Failed to serialize query params: {}", e))
        })?;

        let base_url = self.url(path);
        let full_url = if query_string.is_empty() {
            base_url.clone()
        } else {
            format!("{}?{}", base_url, query_string)
        };

        let request = self.client.get(&base_url).query(query);
        let request = self.apply_auth(request, "GET", &full_url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;

        response::parse_response_bytes(&bytes)
    }

    pub(crate) async fn delete_with_query<T, Q>(&self, path: &str, query: &Q) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        Q: serde::Serialize,
    {
        // Serialize query params to build the full URL for OAuth1 signature
        let query_string = serde_urlencoded::to_string(query).map_err(|e| {
            CrabError::InvalidResponse(format!("Failed to serialize query params: {}", e))
        })?;

        let base_url = self.url(path);
        let full_url = if query_string.is_empty() {
            base_url.clone()
        } else {
            format!("{}?{}", base_url, query_string)
        };

        let request = self.client.delete(&base_url).query(query);
        let request = self.apply_auth(request, "DELETE", &full_url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;

        response::parse_response_bytes(&bytes)
    }

    /// A special variant of the generic GET but for handling the /blog/avatar endpoint specifically.
    /// The endpoint will return binary data if the request sent to it is not OAuth1, so we have to handle the response as a special case.
    pub(crate) async fn get_avatar(&self, path: &str) -> CrabResult<AvatarResponse> {
        let url = self.url(path);
        let request = self.client.get(&url);
        let request = self.apply_auth(request, "GET", &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();

        let bytes = response.bytes().await?;

        // tumblr always returns PNGs
        if &content_type == "image/png" {
            Ok(AvatarResponse::ImageData(bytes.to_vec()))
        } else {
            let response: AvatarResponseUrl = response::parse_response_bytes(&bytes)?;
            Ok(AvatarResponse::ImageUrl {
                avatar_url: response.avatar_url,
            })
        }
    }

    /// Makes a POST request to the API
    ///
    /// This is an internal helper method used by handlers.
    #[allow(dead_code)]
    pub(crate) async fn post<T, B>(&self, path: &str, body: &B) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        let url = self.url(path);
        let request = self.client.post(&url).json(body);
        let request = self.apply_auth(request, "POST", &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;
        response::parse_response_bytes(&bytes)
    }

    /// Makes a PUT request to the API
    ///
    /// This is an internal helper method used by handlers.
    #[allow(dead_code)]
    pub(crate) async fn put<T, B>(&self, path: &str, body: &B) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        let url = self.url(path);
        let request = self.client.put(&url).json(body);
        let request = self.apply_auth(request, "PUT", &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;
        response::parse_response_bytes(&bytes)
    }

    /// Makes a multipart/form-data request to the API using the given HTTP method.
    ///
    /// This is used for uploading media files along with post content.
    /// The request includes a "json" field containing the serialized body,
    /// plus additional fields for each media file keyed by their identifier.
    async fn send_multipart<T, B>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: &B,
        media_sources: std::collections::HashMap<String, media::MediaSource>,
    ) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        let url = self.url(path);

        // Build multipart form
        let mut form = reqwest::multipart::Form::new();

        // Add JSON part
        let json_str = serde_json::to_string(body).map_err(|e| {
            CrabError::InvalidResponse(format!("Failed to serialize request body: {}", e))
        })?;
        form = form.text("json", json_str);

        // Add media parts
        for (identifier, source) in media_sources {
            let bytes = source.read_bytes().map_err(|e| {
                CrabError::InvalidResponse(format!("Failed to read media source: {}", e))
            })?;

            let mut part =
                reqwest::multipart::Part::bytes(bytes).file_name(source.filename().to_string());

            if let Some(mime_type) = source.mime_type() {
                part = part.mime_str(mime_type).map_err(|e| {
                    CrabError::InvalidResponse(format!("Invalid MIME type '{}': {}", mime_type, e))
                })?;
            }

            form = form.part(identifier, part);
        }

        let request = self.client.request(method.clone(), &url).multipart(form);
        let request = self.apply_auth(request, method.as_str(), &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;
        response::parse_response_bytes(&bytes)
    }

    /// Makes a POST request with multipart/form-data to the API
    pub(crate) async fn post_multipart<T, B>(
        &self,
        path: &str,
        body: &B,
        media_sources: std::collections::HashMap<String, media::MediaSource>,
    ) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        self.send_multipart(reqwest::Method::POST, path, body, media_sources)
            .await
    }

    /// Makes a PUT request with multipart/form-data to the API
    pub(crate) async fn put_multipart<T, B>(
        &self,
        path: &str,
        body: &B,
        media_sources: std::collections::HashMap<String, media::MediaSource>,
    ) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        self.send_multipart(reqwest::Method::PUT, path, body, media_sources)
            .await
    }

    /// Makes a DELETE request to the API
    ///
    /// This is an internal helper method used by handlers.
    #[allow(dead_code)]
    pub(crate) async fn delete<T>(&self, path: &str) -> CrabResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.url(path);
        let request = self.client.delete(&url);
        let request = self.apply_auth(request, "DELETE", &url);
        let response = request.send().await?;

        Self::check_rate_limit(&response)?;

        let bytes = response.bytes().await?;
        response::parse_response_bytes(&bytes)
    }
}

/// Builder for constructing a `Crabrave` client
///
/// This builder allows you to configure authentication credentials and client settings
/// before building the final client instance.
pub struct CrabraveBuilder {
    consumer_key: Option<String>,
    consumer_secret: Option<String>,
    access_token: Option<String>,
    access_token_secret: Option<String>,
    user_agent: Option<String>,
    base_url: Option<String>,
}

impl CrabraveBuilder {
    /// Creates a new builder with default settings
    fn new() -> Self {
        Self {
            consumer_key: None,
            consumer_secret: None,
            access_token: None,
            access_token_secret: None,
            user_agent: None,
            base_url: None,
        }
    }

    /// Sets the OAuth consumer key (also known as API key or client ID)
    ///
    /// This is required for all authentication methods.
    pub fn consumer_key(mut self, key: impl Into<String>) -> Self {
        self.consumer_key = Some(key.into());
        self
    }

    /// Sets the OAuth consumer secret (also known as API secret or client secret)
    ///
    /// This is required for OAuth authentication.
    pub fn consumer_secret(mut self, secret: impl Into<String>) -> Self {
        self.consumer_secret = Some(secret.into());
        self
    }

    /// Sets the OAuth access token
    ///
    /// This is the token obtained after completing the OAuth flow.
    pub fn access_token(mut self, token: impl Into<String>) -> Self {
        self.access_token = Some(token.into());
        self
    }

    /// Sets the OAuth1 access token secret
    ///
    /// This is only required for OAuth1 authentication (legacy).
    /// If provided, OAuth1 will be used instead of OAuth2.
    pub fn access_token_secret(mut self, secret: impl Into<String>) -> Self {
        self.access_token_secret = Some(secret.into());
        self
    }

    /// Sets a custom User-Agent header
    ///
    /// If not set, a default User-Agent will be used.
    /// Note: Tumblr requires a User-Agent header and may suspend applications without one.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Sets a custom base URL for API requests
    ///
    /// This is primarily useful for testing. The default is the official Tumblr API URL.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Builds the `Crabrave` client
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Required credentials are missing
    /// - The HTTP client cannot be constructed
    pub fn build(self) -> CrabResult<Crabrave> {
        // Validate required credentials
        let consumer_key = self.consumer_key.ok_or(CrabError::MissingConsumerKey)?;

        // Determine authentication method based on provided credentials
        let auth = if let Some(access_token_secret) = self.access_token_secret {
            // OAuth1 authentication
            let consumer_secret = self
                .consumer_secret
                .ok_or(CrabError::MissingConsumerSecret)?;
            let access_token = self.access_token.ok_or(CrabError::MissingAccessToken)?;

            Auth::OAuth1 {
                consumer_key,
                consumer_secret,
                access_token,
                access_token_secret,
            }
        } else if let Some(access_token) = self.access_token {
            // OAuth2 authentication
            let consumer_secret = self
                .consumer_secret
                .ok_or(CrabError::MissingConsumerSecret)?;

            Auth::OAuth2 {
                consumer_key,
                consumer_secret,
                access_token,
            }
        } else {
            // API key only (read-only)
            Auth::ApiKey { consumer_key }
        };

        // Build headers
        let mut headers = HeaderMap::new();
        let user_agent = self
            .user_agent
            .unwrap_or_else(|| DEFAULT_USER_AGENT.to_string());
        headers.insert(
            USER_AGENT,
            HeaderValue::from_str(&user_agent).map_err(|_| CrabError::InvalidUserAgent)?,
        );

        // Build reqwest client
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .map_err(CrabError::HttpClient)?;

        let base_url = self.base_url.unwrap_or_else(|| BASE_API_URL.to_string());

        Ok(Crabrave {
            client,
            base_url,
            auth: Arc::new(auth),
        })
    }
}

pub(crate) fn empty_object_as_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum EmptyOrValue<T> {
        Value(T),
        Empty {},
    }

    match EmptyOrValue::deserialize(deserializer)? {
        EmptyOrValue::Value(v) => Ok(Some(v)),
        EmptyOrValue::Empty {} => Ok(None),
    }
}

/// Custom deserializer for content blocks that handles both NPF arrays and legacy HTML strings.
/// Legacy posts have `content` as an HTML string, while NPF posts have it as an array of ContentBlock.
/// This deserializer returns the array for NPF posts and an empty Vec for legacy posts.
///
/// Uses explicit Value-based dispatch instead of an untagged enum so that
/// deserialization errors include the block index and type for easier debugging.
pub(crate) fn deserialize_content_blocks<'de, D>(
    deserializer: D,
) -> Result<Vec<npf::ContentBlock>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = serde_json::Value::deserialize(deserializer)?;

    match value {
        serde_json::Value::String(_) => Ok(Vec::new()), // Legacy HTML content
        serde_json::Value::Array(arr) => arr
            .into_iter()
            .enumerate()
            .map(|(i, v)| {
                let block_type = v
                    .get("type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("unknown")
                    .to_owned();
                serde_json::from_value(v).map_err(|e| {
                    serde::de::Error::custom(format!(
                        "content block index {i} (type: {block_type}): {e}"
                    ))
                })
            })
            .collect(),
        other => Err(serde::de::Error::custom(format!(
            "expected array or string for content, got {}",
            kind_of(&other),
        ))),
    }
}

/// Returns a human-readable name for a JSON value kind.
fn kind_of(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_oauth2() {
        let result = Crabrave::builder()
            .consumer_key("test_key")
            .consumer_secret("test_secret")
            .access_token("test_token")
            .build();

        assert!(result.is_ok());
        let crab = result.unwrap();
        assert_eq!(crab.base_url(), BASE_API_URL);
    }

    #[test]
    fn test_builder_oauth1() {
        let result = Crabrave::builder()
            .consumer_key("test_key")
            .consumer_secret("test_secret")
            .access_token("test_token")
            .access_token_secret("test_token_secret")
            .build();

        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_api_key_only() {
        let result = Crabrave::builder().consumer_key("test_key").build();

        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_missing_consumer_key() {
        let result = Crabrave::builder()
            .consumer_secret("test_secret")
            .access_token("test_token")
            .build();

        assert!(matches!(result, Err(CrabError::MissingConsumerKey)));
    }

    #[test]
    fn test_builder_custom_base_url() {
        let custom_url = "https://test.example.com/api";
        let crab = Crabrave::builder()
            .consumer_key("test_key")
            .base_url(custom_url)
            .build()
            .unwrap();

        assert_eq!(crab.base_url(), custom_url);
    }

    #[test]
    fn test_builder_custom_user_agent() {
        let result = Crabrave::builder()
            .consumer_key("test_key")
            .user_agent("CustomAgent/1.0")
            .build();

        assert!(result.is_ok());
    }
}