inferadb 0.1.5

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

use serde::{Deserialize, Serialize};

use crate::client::Client;
use crate::control::Page;
use crate::Error;

/// Client for managing the current user's account.
///
/// Access via `client.account()`.
///
/// ## Example
///
/// ```rust,ignore
/// let account = client.account();
///
/// // Get current account info
/// let info = account.get().await?;
/// println!("Logged in as: {}", info.email);
///
/// // List sessions
/// let sessions = account.sessions().list().await?;
/// ```
#[derive(Clone)]
pub struct AccountClient {
    client: Client,
}

impl AccountClient {
    /// Creates a new account client.
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// Gets the current user's account information.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let account = client.account().get().await?;
    /// println!("Email: {}", account.email);
    /// println!("MFA enabled: {}", account.mfa_enabled);
    /// ```
    #[cfg(feature = "rest")]
    pub async fn get(&self) -> Result<Account, Error> {
        self.client.inner().control_get("/control/v1/account").await
    }

    /// Gets the current user's account information.
    ///
    /// Requires the `rest` feature to be enabled.
    #[cfg(not(feature = "rest"))]
    pub async fn get(&self) -> Result<Account, Error> {
        Err(Error::configuration(
            "REST feature is required for account API",
        ))
    }

    /// Updates the current user's account.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let updated = client.account()
    ///     .update(UpdateAccountRequest::new().with_name("Alice"))
    ///     .await?;
    /// ```
    pub async fn update(&self, request: UpdateAccountRequest) -> Result<Account, Error> {
        #[cfg(feature = "rest")]
        {
            return self
                .client
                .inner()
                .control_patch("/control/v1/users/me", &request)
                .await;
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = request;
            Err(Error::configuration("REST feature is required"))
        }
    }

    /// Returns a client for managing email addresses.
    pub fn emails(&self) -> EmailsClient {
        EmailsClient {
            client: self.client.clone(),
        }
    }

    /// Returns a client for managing sessions.
    pub fn sessions(&self) -> SessionsClient {
        SessionsClient {
            client: self.client.clone(),
        }
    }

    /// Changes the account password.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// client.account()
    ///     .change_password(ChangePasswordRequest {
    ///         current_password: "old_password".into(),
    ///         new_password: "new_secure_password".into(),
    ///     })
    ///     .await?;
    /// ```
    pub async fn change_password(&self, request: ChangePasswordRequest) -> Result<(), Error> {
        #[cfg(feature = "rest")]
        {
            // Password changes may return an empty response or the updated account
            let _: serde_json::Value = self
                .client
                .inner()
                .control_post("/control/v1/users/me/password", &request)
                .await?;
            Ok(())
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = request;
            Err(Error::configuration("REST feature is required"))
        }
    }
}

impl std::fmt::Debug for AccountClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AccountClient").finish_non_exhaustive()
    }
}

/// Information about a user account.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Account {
    /// The account ID (e.g., "usr_abc123").
    pub id: String,
    /// The primary email address.
    pub email: String,
    /// The user's display name.
    pub name: Option<String>,
    /// The account status.
    pub status: AccountStatus,
    /// When the account was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When the account was last updated.
    pub updated_at: chrono::DateTime<chrono::Utc>,
    /// Whether MFA is enabled.
    pub mfa_enabled: bool,
}

/// Account status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountStatus {
    /// Account is active and can be used normally.
    Active,
    /// Account has been suspended by an administrator.
    Suspended,
    /// Account is pending email verification.
    PendingVerification,
}

impl AccountStatus {
    /// Returns `true` if the account is active.
    pub fn is_active(&self) -> bool {
        matches!(self, AccountStatus::Active)
    }

    /// Returns `true` if the account is suspended.
    pub fn is_suspended(&self) -> bool {
        matches!(self, AccountStatus::Suspended)
    }

    /// Returns `true` if the account is pending verification.
    pub fn is_pending_verification(&self) -> bool {
        matches!(self, AccountStatus::PendingVerification)
    }
}

impl std::fmt::Display for AccountStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AccountStatus::Active => write!(f, "active"),
            AccountStatus::Suspended => write!(f, "suspended"),
            AccountStatus::PendingVerification => write!(f, "pending_verification"),
        }
    }
}

/// Request to update an account.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateAccountRequest {
    /// New display name.
    pub name: Option<String>,
}

impl UpdateAccountRequest {
    /// Creates a new empty update request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the display name.
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

/// Request to change account password.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangePasswordRequest {
    /// The current password.
    pub current_password: String,
    /// The new password.
    pub new_password: String,
}

impl ChangePasswordRequest {
    /// Creates a new password change request.
    pub fn new(current_password: impl Into<String>, new_password: impl Into<String>) -> Self {
        Self {
            current_password: current_password.into(),
            new_password: new_password.into(),
        }
    }
}

/// An email address associated with an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Email {
    /// The email address.
    pub address: String,
    /// Whether the email has been verified.
    pub verified: bool,
    /// Whether this is the primary email address.
    pub primary: bool,
    /// When the email was added.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Client for managing email addresses.
#[derive(Clone)]
pub struct EmailsClient {
    client: Client,
}

impl EmailsClient {
    /// Lists all email addresses on the account.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let emails = client.account().emails().list().await?;
    /// for email in emails.items {
    ///     println!("{}: verified={}, primary={}", email.address, email.verified, email.primary);
    /// }
    /// ```
    pub async fn list(&self) -> Result<Page<Email>, Error> {
        #[cfg(feature = "rest")]
        {
            return self
                .client
                .inner()
                .control_get("/control/v1/users/emails")
                .await;
        }
        #[cfg(not(feature = "rest"))]
        Err(Error::configuration("REST feature is required"))
    }

    /// Adds a new email address to the account.
    ///
    /// The email will need to be verified before it can be used.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let email = client.account().emails().add("newemail@example.com").await?;
    /// // Check your inbox for verification email
    /// ```
    pub async fn add(&self, address: impl Into<String>) -> Result<Email, Error> {
        let address = address.into();
        #[cfg(feature = "rest")]
        {
            #[derive(serde::Serialize)]
            struct AddEmailRequest {
                email: String,
            }
            return self
                .client
                .inner()
                .control_post(
                    "/control/v1/users/emails",
                    &AddEmailRequest { email: address },
                )
                .await;
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = address;
            Err(Error::configuration("REST feature is required"))
        }
    }

    /// Removes an email address from the account.
    ///
    /// Cannot remove the primary email address.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// client.account().emails().remove("oldemail@example.com").await?;
    /// ```
    pub async fn remove(&self, address: impl Into<String>) -> Result<(), Error> {
        let address = address.into();
        #[cfg(feature = "rest")]
        {
            // URL-encode the email address for the path
            let encoded = urlencoding::encode(&address);
            let path = format!("/control/v1/users/emails/{}", encoded);
            return self.client.inner().control_delete(&path).await;
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = address;
            Err(Error::configuration("REST feature is required"))
        }
    }

    /// Sets an email address as the primary email.
    ///
    /// The email must be verified first.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// client.account().emails().set_primary("newemail@example.com").await?;
    /// ```
    pub async fn set_primary(&self, address: impl Into<String>) -> Result<(), Error> {
        let address = address.into();
        #[cfg(feature = "rest")]
        {
            #[derive(serde::Serialize)]
            struct SetPrimaryRequest {
                primary: bool,
            }
            // URL-encode the email address for the path
            let encoded = urlencoding::encode(&address);
            let path = format!("/control/v1/users/emails/{}", encoded);
            let _: Email = self
                .client
                .inner()
                .control_patch(&path, &SetPrimaryRequest { primary: true })
                .await?;
            Ok(())
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = address;
            Err(Error::configuration("REST feature is required"))
        }
    }

    /// Resends the verification email for an unverified address.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// client.account().emails().resend_verification("unverified@example.com").await?;
    /// ```
    pub async fn resend_verification(&self, address: impl Into<String>) -> Result<(), Error> {
        let address = address.into();
        #[cfg(feature = "rest")]
        {
            // URL-encode the email address for the path
            let encoded = urlencoding::encode(&address);
            let path = format!("/control/v1/users/emails/{}/resend-verification", encoded);
            let _: serde_json::Value = self.client.inner().control_post_empty(&path).await?;
            Ok(())
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = address;
            Err(Error::configuration("REST feature is required"))
        }
    }
}

impl std::fmt::Debug for EmailsClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmailsClient").finish_non_exhaustive()
    }
}

/// An active session for the account.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    /// The session ID.
    pub id: String,
    /// When the session was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When the session expires.
    pub expires_at: chrono::DateTime<chrono::Utc>,
    /// The IP address that created the session.
    pub ip_address: Option<String>,
    /// The user agent string.
    pub user_agent: Option<String>,
    /// Whether this is the current session.
    pub current: bool,
}

/// Client for managing sessions.
#[derive(Clone)]
pub struct SessionsClient {
    client: Client,
}

impl SessionsClient {
    /// Lists all active sessions.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let sessions = client.account().sessions().list().await?;
    /// for session in sessions.items {
    ///     let current = if session.current { " (current)" } else { "" };
    ///     println!("{}: {} {}{}", session.id, session.ip_address.unwrap_or_default(), session.user_agent.unwrap_or_default(), current);
    /// }
    /// ```
    pub async fn list(&self) -> Result<Page<Session>, Error> {
        #[cfg(feature = "rest")]
        {
            return self
                .client
                .inner()
                .control_get("/control/v1/users/sessions")
                .await;
        }
        #[cfg(not(feature = "rest"))]
        Err(Error::configuration("REST feature is required"))
    }

    /// Revokes a specific session.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// client.account().sessions().revoke("ses_abc123").await?;
    /// ```
    pub async fn revoke(&self, session_id: impl Into<String>) -> Result<(), Error> {
        let session_id = session_id.into();
        #[cfg(feature = "rest")]
        {
            let path = format!("/control/v1/users/sessions/{}", session_id);
            return self.client.inner().control_delete(&path).await;
        }
        #[cfg(not(feature = "rest"))]
        {
            let _ = session_id;
            Err(Error::configuration("REST feature is required"))
        }
    }

    /// Revokes all sessions except the current one.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Log out of all other devices
    /// client.account().sessions().revoke_all_others().await?;
    /// ```
    pub async fn revoke_all_others(&self) -> Result<(), Error> {
        #[cfg(feature = "rest")]
        {
            let _: serde_json::Value = self
                .client
                .inner()
                .control_post_empty("/control/v1/users/sessions/revoke-others")
                .await?;
            Ok(())
        }
        #[cfg(not(feature = "rest"))]
        Err(Error::configuration("REST feature is required"))
    }

    /// Revokes all sessions including the current one.
    ///
    /// **Warning**: This will log out the current session as well.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Log out everywhere
    /// client.account().sessions().revoke_all().await?;
    /// ```
    pub async fn revoke_all(&self) -> Result<(), Error> {
        #[cfg(feature = "rest")]
        {
            let _: serde_json::Value = self
                .client
                .inner()
                .control_post_empty("/control/v1/users/sessions/revoke-all")
                .await?;
            Ok(())
        }
        #[cfg(not(feature = "rest"))]
        Err(Error::configuration("REST feature is required"))
    }
}

impl std::fmt::Debug for SessionsClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionsClient").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::BearerCredentialsConfig;
    use crate::transport::mock::MockTransport;
    use std::sync::Arc;

    async fn create_test_client() -> Client {
        let mock_transport = Arc::new(MockTransport::new());
        Client::builder()
            .url("https://api.example.com")
            .credentials(BearerCredentialsConfig::new("test"))
            .build_with_transport(mock_transport)
            .await
            .unwrap()
    }

    #[test]
    fn test_account_status() {
        assert!(AccountStatus::Active.is_active());
        assert!(!AccountStatus::Active.is_suspended());
        assert!(!AccountStatus::Active.is_pending_verification());

        assert!(!AccountStatus::Suspended.is_active());
        assert!(AccountStatus::Suspended.is_suspended());

        assert!(AccountStatus::PendingVerification.is_pending_verification());
    }

    #[test]
    fn test_account_status_display() {
        assert_eq!(AccountStatus::Active.to_string(), "active");
        assert_eq!(AccountStatus::Suspended.to_string(), "suspended");
        assert_eq!(
            AccountStatus::PendingVerification.to_string(),
            "pending_verification"
        );
    }

    #[test]
    fn test_update_account_request() {
        let req = UpdateAccountRequest::new().with_name("Alice");
        assert_eq!(req.name, Some("Alice".to_string()));
    }

    #[test]
    fn test_change_password_request() {
        let req = ChangePasswordRequest::new("old", "new");
        assert_eq!(req.current_password, "old");
        assert_eq!(req.new_password, "new");
    }

    #[tokio::test]
    async fn test_debug_impls() {
        let client = create_test_client().await;
        let account = AccountClient::new(client.clone());

        assert!(format!("{:?}", account).contains("AccountClient"));
        assert!(format!("{:?}", account.emails()).contains("EmailsClient"));
        assert!(format!("{:?}", account.sessions()).contains("SessionsClient"));
    }

    // Additional tests for Clone implementations
    #[tokio::test]
    async fn test_account_client_clone() {
        let client = create_test_client().await;
        let account = AccountClient::new(client);
        let _cloned = account.clone();
    }

    #[tokio::test]
    async fn test_emails_client_clone() {
        let client = create_test_client().await;
        let account = AccountClient::new(client);
        let emails = account.emails();
        let _cloned = emails.clone();
    }

    #[tokio::test]
    async fn test_sessions_client_clone() {
        let client = create_test_client().await;
        let account = AccountClient::new(client);
        let sessions = account.sessions();
        let _cloned = sessions.clone();
    }

    // Test Account type serialization
    #[test]
    fn test_account_serde() {
        let json = r#"{
            "id": "usr_abc123",
            "email": "test@example.com",
            "name": "Test User",
            "status": "active",
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "mfa_enabled": false
        }"#;
        let account: Account = serde_json::from_str(json).unwrap();
        assert_eq!(account.id, "usr_abc123");
        assert_eq!(account.email, "test@example.com");
        assert_eq!(account.name, Some("Test User".to_string()));
        assert!(account.status.is_active());
        assert!(!account.mfa_enabled);
    }

    #[test]
    fn test_account_clone() {
        let account = Account {
            id: "usr_abc123".to_string(),
            email: "test@example.com".to_string(),
            name: Some("Test".to_string()),
            status: AccountStatus::Active,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            mfa_enabled: true,
        };
        let cloned = account.clone();
        assert_eq!(cloned.id, "usr_abc123");
        assert!(cloned.mfa_enabled);
    }

    // Test Email type
    #[test]
    fn test_email_serde() {
        let json = r#"{
            "address": "test@example.com",
            "verified": true,
            "primary": true,
            "created_at": "2024-01-01T00:00:00Z"
        }"#;
        let email: Email = serde_json::from_str(json).unwrap();
        assert_eq!(email.address, "test@example.com");
        assert!(email.verified);
        assert!(email.primary);
    }

    #[test]
    fn test_email_clone() {
        let email = Email {
            address: "test@example.com".to_string(),
            verified: false,
            primary: false,
            created_at: chrono::Utc::now(),
        };
        let cloned = email.clone();
        assert_eq!(cloned.address, "test@example.com");
        assert!(!cloned.verified);
    }

    // Test Session type
    #[test]
    fn test_session_serde() {
        let json = r#"{
            "id": "ses_abc123",
            "created_at": "2024-01-01T00:00:00Z",
            "expires_at": "2024-02-01T00:00:00Z",
            "ip_address": "192.168.1.1",
            "user_agent": "Mozilla/5.0",
            "current": true
        }"#;
        let session: Session = serde_json::from_str(json).unwrap();
        assert_eq!(session.id, "ses_abc123");
        assert!(session.current);
        assert_eq!(session.ip_address, Some("192.168.1.1".to_string()));
        assert_eq!(session.user_agent, Some("Mozilla/5.0".to_string()));
    }

    #[test]
    fn test_session_clone() {
        let session = Session {
            id: "ses_abc".to_string(),
            created_at: chrono::Utc::now(),
            expires_at: chrono::Utc::now(),
            ip_address: None,
            user_agent: None,
            current: false,
        };
        let cloned = session.clone();
        assert_eq!(cloned.id, "ses_abc");
        assert!(!cloned.current);
    }

    // Test UpdateAccountRequest serialization
    #[test]
    fn test_update_account_request_serde() {
        let req = UpdateAccountRequest::new().with_name("New Name");
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("New Name"));
    }

    // Test ChangePasswordRequest serialization
    #[test]
    fn test_change_password_request_serde() {
        let req = ChangePasswordRequest::new("old_pass", "new_pass");
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("old_pass"));
        assert!(json.contains("new_pass"));
    }

    #[test]
    fn test_change_password_request_clone() {
        let req = ChangePasswordRequest::new("old", "new");
        let cloned = req.clone();
        assert_eq!(cloned.current_password, "old");
        assert_eq!(cloned.new_password, "new");
    }

    #[test]
    fn test_update_account_request_clone() {
        let req = UpdateAccountRequest::new().with_name("Test");
        let cloned = req.clone();
        assert_eq!(cloned.name, Some("Test".to_string()));
    }
}

#[cfg(test)]
#[cfg(feature = "rest")]
mod wiremock_tests {
    use super::*;
    use crate::auth::BearerCredentialsConfig;
    use crate::Client;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn create_mock_client(server: &MockServer) -> Client {
        Client::builder()
            .url(server.uri())
            .insecure()
            .credentials(BearerCredentialsConfig::new("test_token"))
            .build()
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn test_get_account() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/account"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "usr_123",
                "email": "user@example.com",
                "name": "Test User",
                "status": "active",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z",
                "mfa_enabled": false
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().get().await;

        assert!(result.is_ok());
        let account = result.unwrap();
        assert_eq!(account.id, "usr_123");
        assert_eq!(account.email, "user@example.com");
    }

    #[tokio::test]
    async fn test_get_account_unauthorized() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/account"))
            .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
                "error": "Unauthorized"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().get().await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_update_account() {
        let server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/control/v1/users/me"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "usr_123",
                "email": "user@example.com",
                "name": "Updated Name",
                "status": "active",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-02T00:00:00Z",
                "mfa_enabled": false
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let request = UpdateAccountRequest::new().with_name("Updated Name");
        let result = client.account().update(request).await;

        assert!(result.is_ok());
        let account = result.unwrap();
        assert_eq!(account.name, Some("Updated Name".to_string()));
    }

    #[tokio::test]
    async fn test_change_password() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/control/v1/users/me/password"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let request = ChangePasswordRequest::new("old_pass", "new_pass");
        let result = client.account().change_password(request).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_emails() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/users/emails"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "address": "primary@example.com",
                        "verified": true,
                        "primary": true,
                        "created_at": "2024-01-01T00:00:00Z"
                    },
                    {
                        "address": "secondary@example.com",
                        "verified": false,
                        "primary": false,
                        "created_at": "2024-01-02T00:00:00Z"
                    }
                ],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 2
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().emails().list().await;

        assert!(result.is_ok());
        let page = result.unwrap();
        assert_eq!(page.items.len(), 2);
        assert_eq!(page.items[0].address, "primary@example.com");
    }

    #[tokio::test]
    async fn test_add_email() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/control/v1/users/emails"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "address": "new@example.com",
                "verified": false,
                "primary": false,
                "created_at": "2024-01-01T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().emails().add("new@example.com").await;

        assert!(result.is_ok());
        let email = result.unwrap();
        assert_eq!(email.address, "new@example.com");
        assert!(!email.verified);
    }

    #[tokio::test]
    async fn test_remove_email() {
        let server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/control/v1/users/emails/old%40example.com"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().emails().remove("old@example.com").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_sessions() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/users/sessions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "id": "sess_123",
                        "ip_address": "192.168.1.1",
                        "user_agent": "Mozilla/5.0",
                        "created_at": "2024-01-01T00:00:00Z",
                        "expires_at": "2024-02-01T00:00:00Z",
                        "current": true
                    }
                ],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 1
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().sessions().list().await;

        assert!(result.is_ok());
        let page = result.unwrap();
        assert_eq!(page.items.len(), 1);
        assert!(page.items[0].current);
    }

    #[tokio::test]
    async fn test_revoke_session() {
        let server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/control/v1/users/sessions/sess_123"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().sessions().revoke("sess_123").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_revoke_all_sessions() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/control/v1/users/sessions/revoke-all"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let result = client.account().sessions().revoke_all().await;

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