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
//! Team management for the control plane.

use serde::{Deserialize, Serialize};

use crate::client::Client;
use crate::control::{Page, SortOrder};
use crate::Error;

/// Client for team management operations.
///
/// Access via `org.teams()`.
///
/// ## Example
///
/// ```rust,ignore
/// let teams = org.teams();
///
/// // Create a team
/// let team = teams.create(CreateTeamRequest::new("Engineering")).await?;
///
/// // List all teams
/// let list = teams.list().await?;
///
/// // Add member to team
/// teams.add_member(&team.id, "user:alice").await?;
/// ```
#[derive(Clone)]
pub struct TeamsClient {
    client: Client,
    organization_id: String,
}

impl TeamsClient {
    /// Creates a new teams client.
    pub(crate) fn new(client: Client, organization_id: impl Into<String>) -> Self {
        Self {
            client,
            organization_id: organization_id.into(),
        }
    }

    /// Returns the organization ID.
    pub fn organization_id(&self) -> &str {
        &self.organization_id
    }

    /// Lists all teams in the organization.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let teams = org.teams().list().await?;
    /// for team in teams.items {
    ///     println!("{}: {}", team.id, team.name);
    /// }
    /// ```
    pub fn list(&self) -> ListTeamsRequest {
        ListTeamsRequest {
            client: self.client.clone(),
            organization_id: self.organization_id.clone(),
            limit: None,
            cursor: None,
            sort: None,
        }
    }

    /// Creates a new team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let team = org.teams().create(CreateTeamRequest::new("Engineering")
    ///     .with_description("Backend engineering team")
    /// ).await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn create(&self, request: CreateTeamRequest) -> Result<TeamInfo, Error> {
        let path = format!("/control/v1/organizations/{}/teams", self.organization_id);
        self.client.inner().control_post(&path, &request).await
    }

    /// Creates a new team.
    #[cfg(not(feature = "rest"))]
    pub async fn create(&self, _request: CreateTeamRequest) -> Result<TeamInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Gets a team by ID.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let team = org.teams().get("team_abc123").await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn get(&self, team_id: impl Into<String>) -> Result<TeamInfo, Error> {
        let path = format!(
            "/control/v1/organizations/{}/teams/{}",
            self.organization_id,
            team_id.into()
        );
        self.client.inner().control_get(&path).await
    }

    /// Gets a team by ID.
    #[cfg(not(feature = "rest"))]
    pub async fn get(&self, _team_id: impl Into<String>) -> Result<TeamInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Updates a team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let team = org.teams().update("team_abc123", UpdateTeamRequest::new()
    ///     .with_name("New Name")
    /// ).await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn update(
        &self,
        team_id: impl Into<String>,
        request: UpdateTeamRequest,
    ) -> Result<TeamInfo, Error> {
        let path = format!(
            "/control/v1/organizations/{}/teams/{}",
            self.organization_id,
            team_id.into()
        );
        self.client.inner().control_patch(&path, &request).await
    }

    /// Updates a team.
    #[cfg(not(feature = "rest"))]
    pub async fn update(
        &self,
        _team_id: impl Into<String>,
        _request: UpdateTeamRequest,
    ) -> Result<TeamInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Deletes a team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// org.teams().delete("team_abc123").await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn delete(&self, team_id: impl Into<String>) -> Result<(), Error> {
        let path = format!(
            "/control/v1/organizations/{}/teams/{}",
            self.organization_id,
            team_id.into()
        );
        self.client.inner().control_delete(&path).await
    }

    /// Deletes a team.
    #[cfg(not(feature = "rest"))]
    pub async fn delete(&self, _team_id: impl Into<String>) -> Result<(), Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Adds a member to a team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// org.teams().add_member("team_abc123", "user_xyz").await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn add_member(
        &self,
        team_id: impl Into<String>,
        user_id: impl Into<String>,
    ) -> Result<(), Error> {
        #[derive(serde::Serialize)]
        struct AddMemberBody {
            user_id: String,
        }
        let path = format!(
            "/control/v1/organizations/{}/teams/{}/members",
            self.organization_id,
            team_id.into()
        );
        let body = AddMemberBody {
            user_id: user_id.into(),
        };
        self.client
            .inner()
            .control_post::<_, ()>(&path, &body)
            .await
    }

    /// Adds a member to a team.
    #[cfg(not(feature = "rest"))]
    pub async fn add_member(
        &self,
        _team_id: impl Into<String>,
        _user_id: impl Into<String>,
    ) -> Result<(), Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Removes a member from a team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// org.teams().remove_member("team_abc123", "user_xyz").await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn remove_member(
        &self,
        team_id: impl Into<String>,
        user_id: impl Into<String>,
    ) -> Result<(), Error> {
        let path = format!(
            "/control/v1/organizations/{}/teams/{}/members/{}",
            self.organization_id,
            team_id.into(),
            user_id.into()
        );
        self.client.inner().control_delete(&path).await
    }

    /// Removes a member from a team.
    #[cfg(not(feature = "rest"))]
    pub async fn remove_member(
        &self,
        _team_id: impl Into<String>,
        _user_id: impl Into<String>,
    ) -> Result<(), Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Lists members of a team.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let members = org.teams().list_members("team_abc123").await?;
    /// for member in members.items {
    ///     println!("{}: {}", member.user_id, member.role);
    /// }
    /// ```
    pub fn list_members(&self, team_id: impl Into<String>) -> ListTeamMembersRequest {
        ListTeamMembersRequest {
            client: self.client.clone(),
            organization_id: self.organization_id.clone(),
            team_id: team_id.into(),
            limit: None,
            cursor: None,
        }
    }
}

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

/// Information about a team.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamInfo {
    /// The team ID (e.g., "team_abc123").
    pub id: String,
    /// The organization ID that owns this team.
    pub organization_id: String,
    /// The team name.
    pub name: String,
    /// Description of the team.
    pub description: Option<String>,
    /// Number of members in the team.
    pub member_count: u32,
    /// When the team was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When the team was last updated.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Information about a team member.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamMemberInfo {
    /// The user ID.
    pub user_id: String,
    /// The user's email.
    pub email: String,
    /// The user's display name.
    pub name: Option<String>,
    /// Role within the team.
    pub role: TeamRole,
    /// When the member joined the team.
    pub joined_at: chrono::DateTime<chrono::Utc>,
}

/// Role within a team.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TeamRole {
    /// Team owner with full permissions.
    Owner,
    /// Team administrator.
    Admin,
    /// Regular team member.
    #[default]
    Member,
}

impl std::fmt::Display for TeamRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TeamRole::Owner => write!(f, "owner"),
            TeamRole::Admin => write!(f, "admin"),
            TeamRole::Member => write!(f, "member"),
        }
    }
}

/// Request to create a new team.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreateTeamRequest {
    /// The team name.
    pub name: String,
    /// Description of the team.
    pub description: Option<String>,
}

impl CreateTeamRequest {
    /// Creates a new request with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
        }
    }

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

/// Request to update a team.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateTeamRequest {
    /// New name for the team.
    pub name: Option<String>,
    /// New description.
    pub description: Option<String>,
}

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

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

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

/// Request to list teams.
pub struct ListTeamsRequest {
    client: Client,
    organization_id: String,
    limit: Option<usize>,
    cursor: Option<String>,
    sort: Option<SortOrder>,
}

impl ListTeamsRequest {
    /// Sets the maximum number of results to return.
    #[must_use]
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

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

    /// Sets the sort order.
    #[must_use]
    pub fn sort(mut self, order: SortOrder) -> Self {
        self.sort = Some(order);
        self
    }

    #[cfg(feature = "rest")]
    async fn execute(self) -> Result<Page<TeamInfo>, Error> {
        let mut path = format!("/control/v1/organizations/{}/teams", self.organization_id);
        let mut query_parts = Vec::new();

        if let Some(limit) = self.limit {
            query_parts.push(format!("limit={}", limit));
        }
        if let Some(cursor) = &self.cursor {
            query_parts.push(format!("cursor={}", urlencoding::encode(cursor)));
        }
        if let Some(sort) = &self.sort {
            query_parts.push(format!("sort={}", sort.as_str()));
        }

        if !query_parts.is_empty() {
            path.push('?');
            path.push_str(&query_parts.join("&"));
        }

        self.client.inner().control_get(&path).await
    }

    #[cfg(not(feature = "rest"))]
    async fn execute(self) -> Result<Page<TeamInfo>, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }
}

impl std::future::IntoFuture for ListTeamsRequest {
    type Output = Result<Page<TeamInfo>, Error>;
    type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.execute())
    }
}

/// Request to list team members.
pub struct ListTeamMembersRequest {
    client: Client,
    organization_id: String,
    team_id: String,
    limit: Option<usize>,
    cursor: Option<String>,
}

impl ListTeamMembersRequest {
    /// Sets the maximum number of results to return.
    #[must_use]
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

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

    #[cfg(feature = "rest")]
    async fn execute(self) -> Result<Page<TeamMemberInfo>, Error> {
        let mut path = format!(
            "/control/v1/organizations/{}/teams/{}/members",
            self.organization_id, self.team_id
        );
        let mut query_parts = Vec::new();

        if let Some(limit) = self.limit {
            query_parts.push(format!("limit={}", limit));
        }
        if let Some(cursor) = &self.cursor {
            query_parts.push(format!("cursor={}", urlencoding::encode(cursor)));
        }

        if !query_parts.is_empty() {
            path.push('?');
            path.push_str(&query_parts.join("&"));
        }

        self.client.inner().control_get(&path).await
    }

    #[cfg(not(feature = "rest"))]
    async fn execute(self) -> Result<Page<TeamMemberInfo>, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }
}

impl std::future::IntoFuture for ListTeamMembersRequest {
    type Output = Result<Page<TeamMemberInfo>, Error>;
    type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.execute())
    }
}

#[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_team_role() {
        assert_eq!(TeamRole::default(), TeamRole::Member);
        assert_eq!(TeamRole::Owner.to_string(), "owner");
        assert_eq!(TeamRole::Admin.to_string(), "admin");
        assert_eq!(TeamRole::Member.to_string(), "member");
    }

    #[test]
    fn test_create_team_request() {
        let req = CreateTeamRequest::new("Engineering").with_description("Backend team");

        assert_eq!(req.name, "Engineering");
        assert_eq!(req.description, Some("Backend team".to_string()));
    }

    #[test]
    fn test_update_team_request() {
        let req = UpdateTeamRequest::new()
            .with_name("New Name")
            .with_description("New description");

        assert_eq!(req.name, Some("New Name".to_string()));
        assert_eq!(req.description, Some("New description".to_string()));
    }

    #[tokio::test]
    async fn test_teams_client_accessors() {
        let client = create_test_client().await;
        let teams = TeamsClient::new(client, "org_test");
        assert_eq!(teams.organization_id(), "org_test");
    }

    #[tokio::test]
    async fn test_teams_client_debug() {
        let client = create_test_client().await;
        let teams = TeamsClient::new(client, "org_test");
        let debug = format!("{:?}", teams);
        assert!(debug.contains("TeamsClient"));
        assert!(debug.contains("org_test"));
    }

    #[tokio::test]
    async fn test_list_teams_request_builders() {
        let client = create_test_client().await;
        let teams = TeamsClient::new(client, "org_test");

        // Test all builder methods
        let _request = teams
            .list()
            .limit(50)
            .cursor("cursor_xyz")
            .sort(SortOrder::Descending);

        // Just verify the builder compiles and returns a request
    }

    #[tokio::test]
    async fn test_list_team_members_request_builders() {
        let client = create_test_client().await;
        let teams = TeamsClient::new(client, "org_test");

        // Test all builder methods
        let _request = teams
            .list_members("team_abc123")
            .limit(50)
            .cursor("cursor_xyz");

        // Just verify the builder compiles and returns a request
    }

    // Additional tests for Clone implementations and serde
    #[tokio::test]
    async fn test_teams_client_clone() {
        let client = create_test_client().await;
        let teams = TeamsClient::new(client, "org_test");
        let cloned = teams.clone();
        assert_eq!(cloned.organization_id(), "org_test");
    }

    #[test]
    fn test_team_info_serde() {
        let json = r#"{
            "id": "team_abc123",
            "organization_id": "org_test",
            "name": "Engineering",
            "description": "Backend team",
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "member_count": 5
        }"#;
        let team: TeamInfo = serde_json::from_str(json).unwrap();
        assert_eq!(team.id, "team_abc123");
        assert_eq!(team.name, "Engineering");
        assert_eq!(team.description, Some("Backend team".to_string()));
        assert_eq!(team.member_count, 5);
    }

    #[test]
    fn test_team_info_clone() {
        let team = TeamInfo {
            id: "team_123".to_string(),
            organization_id: "org_123".to_string(),
            name: "Test Team".to_string(),
            description: None,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            member_count: 0,
        };
        let cloned = team.clone();
        assert_eq!(cloned.id, "team_123");
        assert_eq!(cloned.name, "Test Team");
    }

    #[test]
    fn test_team_member_info_serde() {
        let json = r#"{
            "user_id": "user_abc123",
            "email": "test@example.com",
            "name": "Alice",
            "role": "admin",
            "joined_at": "2024-01-01T00:00:00Z"
        }"#;
        let member: TeamMemberInfo = serde_json::from_str(json).unwrap();
        assert_eq!(member.user_id, "user_abc123");
        assert_eq!(member.email, "test@example.com");
        assert_eq!(member.role, TeamRole::Admin);
    }

    #[test]
    fn test_team_member_info_clone() {
        let member = TeamMemberInfo {
            user_id: "user_123".to_string(),
            email: "test@test.com".to_string(),
            name: Some("Test".to_string()),
            role: TeamRole::Owner,
            joined_at: chrono::Utc::now(),
        };
        let cloned = member.clone();
        assert_eq!(cloned.user_id, "user_123");
        assert_eq!(cloned.role, TeamRole::Owner);
    }

    #[test]
    fn test_team_role_serde() {
        let roles = vec![
            (TeamRole::Owner, "\"owner\""),
            (TeamRole::Admin, "\"admin\""),
            (TeamRole::Member, "\"member\""),
        ];
        for (role, expected) in roles {
            let json = serde_json::to_string(&role).unwrap();
            assert_eq!(json, expected);
            let parsed: TeamRole = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, role);
        }
    }

    #[test]
    fn test_create_team_request_clone() {
        let req = CreateTeamRequest::new("Test").with_description("Desc");
        let cloned = req.clone();
        assert_eq!(cloned.name, "Test");
        assert_eq!(cloned.description, Some("Desc".to_string()));
    }

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

#[cfg(all(test, 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_list_teams() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations/org_123/teams"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "id": "team_1",
                        "organization_id": "org_123",
                        "name": "Engineering",
                        "description": "Backend team",
                        "member_count": 5,
                        "created_at": "2024-01-01T00:00:00Z",
                        "updated_at": "2024-01-02T00:00:00Z"
                    }
                ],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 1
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams.list().await;

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

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

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations/org_123/teams"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 0
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams
            .list()
            .limit(10)
            .cursor("cursor_abc")
            .sort(SortOrder::Descending)
            .await;

        assert!(result.is_ok());
    }

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

        Mock::given(method("POST"))
            .and(path("/control/v1/organizations/org_123/teams"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "team_new",
                "organization_id": "org_123",
                "name": "New Team",
                "description": "A new team",
                "member_count": 0,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams
            .create(CreateTeamRequest::new("New Team").with_description("A new team"))
            .await;

        assert!(result.is_ok());
        let team = result.unwrap();
        assert_eq!(team.name, "New Team");
    }

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

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations/org_123/teams/team_abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "team_abc",
                "organization_id": "org_123",
                "name": "Test Team",
                "description": "Test",
                "member_count": 3,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-02T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams.get("team_abc").await;

        assert!(result.is_ok());
        let team = result.unwrap();
        assert_eq!(team.id, "team_abc");
    }

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

        Mock::given(method("PATCH"))
            .and(path("/control/v1/organizations/org_123/teams/team_abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "team_abc",
                "organization_id": "org_123",
                "name": "Updated Team",
                "description": "Updated description",
                "member_count": 3,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-03T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams
            .update(
                "team_abc",
                UpdateTeamRequest::new().with_name("Updated Team"),
            )
            .await;

        assert!(result.is_ok());
        let team = result.unwrap();
        assert_eq!(team.name, "Updated Team");
    }

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

        Mock::given(method("DELETE"))
            .and(path("/control/v1/organizations/org_123/teams/team_abc"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams.delete("team_abc").await;

        assert!(result.is_ok());
    }

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

        Mock::given(method("POST"))
            .and(path(
                "/control/v1/organizations/org_123/teams/team_abc/members",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_string("null"))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams.add_member("team_abc", "user_xyz").await;

        assert!(result.is_ok());
    }

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

        Mock::given(method("DELETE"))
            .and(path(
                "/control/v1/organizations/org_123/teams/team_abc/members/user_xyz",
            ))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let teams = TeamsClient::new(client, "org_123");
        let result = teams.remove_member("team_abc", "user_xyz").await;

        assert!(result.is_ok());
    }

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

        Mock::given(method("GET"))
            .and(path(
                "/control/v1/organizations/org_123/teams/team_abc/members",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "user_id": "user_1",
                        "email": "user1@example.com",
                        "name": "User One",
                        "role": "owner",
                        "joined_at": "2024-01-01T00:00:00Z"
                    },
                    {
                        "user_id": "user_2",
                        "email": "user2@example.com",
                        "role": "member",
                        "joined_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 teams = TeamsClient::new(client, "org_123");
        let result = teams.list_members("team_abc").await;

        assert!(result.is_ok());
        let page = result.unwrap();
        assert_eq!(page.items.len(), 2);
        assert_eq!(page.items[0].role, TeamRole::Owner);
    }
}