metabase-api-rs 0.1.0-beta.3

A simplified Rust client for the Metabase API (Beta release - feature complete)
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
//! Metabase client implementation

use crate::api::auth::{AuthManager, Credentials};
use crate::api::CardListParams;
use crate::core::error::{Error, Result};
use crate::core::models::common::{CardId, ExportFormat};
#[cfg(feature = "query-builder")]
use crate::core::models::mbql::MbqlQuery;
use crate::core::models::{
    Card, Collection, Dashboard, DatabaseMetadata, DatasetQuery, Field, HealthStatus, MetabaseId,
    NativeQuery, Pagination, QueryResult, SyncResult, User,
};
use crate::service::ServiceManager;
use crate::transport::http_provider_safe::{HttpClientAdapter, HttpProviderSafe};
use crate::transport::HttpClient;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;

#[cfg(feature = "cache")]
use crate::cache::{cache_key, CacheConfig, CacheLayer};

/// The main client for interacting with Metabase API
#[derive(Clone)]
pub struct MetabaseClient {
    pub(super) auth_manager: AuthManager,
    pub(super) base_url: String,
    pub(super) service_manager: ServiceManager,
    #[cfg(feature = "cache")]
    pub(super) cache: CacheLayer,
}

impl MetabaseClient {
    /// Creates a new MetabaseClient instance
    pub fn new(base_url: impl Into<String>) -> Result<Self> {
        let base_url = base_url.into();

        // Validate URL
        if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
            return Err(Error::Config(
                "Invalid URL: must start with http:// or https://".to_string(),
            ));
        }

        let http_client = HttpClient::new(&base_url)?;
        let auth_manager = AuthManager::new();

        // Create HttpProviderSafe adapter for ServiceManager
        let http_provider: Arc<dyn HttpProviderSafe> =
            Arc::new(HttpClientAdapter::new(http_client));
        let service_manager = ServiceManager::new(http_provider);

        Ok(Self {
            auth_manager,
            base_url,
            service_manager,
            #[cfg(feature = "cache")]
            cache: CacheLayer::new(CacheConfig::default()),
        })
    }

    /// Creates a new MetabaseClient with custom cache configuration
    #[cfg(feature = "cache")]
    pub fn with_cache(base_url: impl Into<String>, cache_config: CacheConfig) -> Result<Self> {
        let base_url = base_url.into();

        // Validate URL
        if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
            return Err(Error::Config(
                "Invalid URL: must start with http:// or https://".to_string(),
            ));
        }

        let http_client = HttpClient::new(&base_url)?;
        let auth_manager = AuthManager::new();

        // Create HttpProviderSafe adapter for ServiceManager
        let http_provider: Arc<dyn HttpProviderSafe> =
            Arc::new(HttpClientAdapter::new(http_client));
        let service_manager = ServiceManager::new(http_provider);

        Ok(Self {
            auth_manager,
            base_url,
            service_manager,
            cache: CacheLayer::new(cache_config),
        })
    }

    /// Gets the base URL of the client
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Checks if the client is authenticated
    pub fn is_authenticated(&self) -> bool {
        self.auth_manager.is_authenticated()
    }

    /// Checks if cache is enabled
    #[cfg(feature = "cache")]
    pub fn is_cache_enabled(&self) -> bool {
        self.cache.is_enabled()
    }

    /// Sets the cache enabled state
    #[cfg(feature = "cache")]
    pub fn set_cache_enabled(&mut self, enabled: bool) {
        self.cache.set_enabled(enabled);
    }

    /// Checks if cache is enabled (always false when cache feature is disabled)
    #[cfg(not(feature = "cache"))]
    pub fn is_cache_enabled(&self) -> bool {
        false
    }

    /// Sets the cache enabled state (no-op when cache feature is disabled)
    #[cfg(not(feature = "cache"))]
    pub fn set_cache_enabled(&mut self, _enabled: bool) {
        // No-op when cache feature is disabled
    }

    /// Authenticates with the Metabase API
    pub async fn authenticate(&mut self, credentials: Credentials) -> Result<()> {
        // Use ServiceManager for authentication
        let (session_id, user) = self
            .service_manager
            .auth_service()
            .ok_or_else(|| Error::Config("Auth service not available".to_string()))?
            .authenticate(credentials)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        self.auth_manager.set_session(session_id, user);
        Ok(())
    }

    /// Logs out from the Metabase API
    pub async fn logout(&mut self) -> Result<()> {
        if !self.is_authenticated() {
            return Ok(());
        }

        // Get session ID before clearing
        let session_id = self.auth_manager.get_session_id();

        if let Some(id) = session_id {
            // Use ServiceManager for logout
            self.service_manager
                .auth_service()
                .ok_or_else(|| Error::Config("Auth service not available".to_string()))?
                .logout(&id)
                .await
                .map_err(|e| Error::Config(format!("Service error: {}", e)))?;
        }

        // Clear local session
        self.auth_manager.clear_session();
        Ok(())
    }

    /// Performs a health check on the Metabase API
    pub async fn health_check(&self) -> Result<HealthStatus> {
        // Use ServiceManager for health check
        self.service_manager
            .auth_service()
            .ok_or_else(|| Error::Config("Auth service not available".to_string()))?
            .health_check()
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Gets the current authenticated user
    pub async fn get_current_user(&self) -> Result<User> {
        if !self.is_authenticated() {
            return Err(Error::Authentication("Not authenticated".to_string()));
        }

        let session_id = self
            .auth_manager
            .get_session_id()
            .ok_or_else(|| Error::Authentication("No session available".to_string()))?;

        // Use ServiceManager for getting current user
        self.service_manager
            .auth_service()
            .ok_or_else(|| Error::Config("Auth service not available".to_string()))?
            .get_current_user(&session_id)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Card Operations ====================

    /// Gets a card by ID
    pub async fn get_card(&self, id: i64) -> Result<Card> {
        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("card", id);
            if let Some(card) = self.cache.get_metadata::<Card>(&cache_key) {
                return Ok(card);
            }
        }

        // Use ServiceManager for layered architecture
        let card = self
            .service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .get_card(CardId(id as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("card", id);
            let _ = self.cache.set_metadata(cache_key, &card);
        }

        Ok(card)
    }

    /// Lists all cards
    pub async fn list_cards(&self, params: Option<CardListParams>) -> Result<Vec<Card>> {
        use crate::repository::card::CardFilterParams;

        // Convert CardListParams to CardFilterParams and PaginationParams
        let filters = params.map(|p| CardFilterParams {
            f: p.f,
            model_type: p.model_type,
            archived: None,
            collection_id: None,
        });

        // Use ServiceManager for layered architecture
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .list_cards(None, filters)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Creates a new card
    pub async fn create_card(&self, card: Card) -> Result<Card> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to create card".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture with validation
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .create_card(card)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Updates an existing card
    pub async fn update_card(&self, id: i64, updates: serde_json::Value) -> Result<Card> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to update card".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("card", id);
            self.cache.invalidate(&cache_key);
        }

        // First, get the existing card
        let service = self
            .service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?;

        let mut existing_card = service
            .get_card(CardId(id as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        // Merge the updates into the existing card
        if let Some(name) = updates.get("name").and_then(|v| v.as_str()) {
            existing_card.name = name.to_string();
        }
        if let Some(description) = updates.get("description") {
            existing_card.description = if description.is_null() {
                None
            } else {
                description.as_str().map(|s| s.to_string())
            };
        }
        if let Some(display) = updates.get("display").and_then(|v| v.as_str()) {
            existing_card.display = display.to_string();
        }
        if let Some(dataset_query) = updates.get("dataset_query") {
            existing_card.dataset_query = Some(dataset_query.clone());
        }
        if let Some(visualization_settings) = updates.get("visualization_settings") {
            existing_card.visualization_settings = visualization_settings.clone();
        }

        // Use ServiceManager for layered architecture
        service
            .update_card(CardId(id as i32), existing_card)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Deletes a card
    pub async fn delete_card(&self, id: i64) -> Result<()> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to delete card".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("card", id);
            self.cache.invalidate(&cache_key);
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .delete_card(CardId(id as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Collection Operations ====================

    /// Gets a collection by ID
    pub async fn get_collection(&self, id: MetabaseId) -> Result<Collection> {
        use crate::core::models::common::CollectionId;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("collection", id.0);
            if let Some(collection) = self.cache.get_metadata::<Collection>(&cache_key) {
                return Ok(collection);
            }
        }

        // Use ServiceManager for layered architecture
        let collection = self
            .service_manager
            .collection_service()
            .ok_or_else(|| Error::Config("Collection service not available".to_string()))?
            .get_collection(CollectionId(id.0 as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("collection", id.0);
            let _ = self.cache.set_metadata(cache_key, &collection);
        }

        Ok(collection)
    }

    /// Lists all collections
    pub async fn list_collections(&self) -> Result<Vec<Collection>> {
        // Use ServiceManager for layered architecture
        self.service_manager
            .collection_service()
            .ok_or_else(|| Error::Config("Collection service not available".to_string()))?
            .list_collections(None, None)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Creates a new collection
    pub async fn create_collection(&self, collection: Collection) -> Result<Collection> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to create collection".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture with validation
        self.service_manager
            .collection_service()
            .ok_or_else(|| Error::Config("Collection service not available".to_string()))?
            .create_collection(collection)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Updates an existing collection
    pub async fn update_collection(
        &self,
        id: MetabaseId,
        updates: serde_json::Value,
    ) -> Result<Collection> {
        use crate::core::models::common::CollectionId;

        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to update collection".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("collection", id.0);
            self.cache.invalidate(&cache_key);
        }

        // First, get the existing collection
        let service = self
            .service_manager
            .collection_service()
            .ok_or_else(|| Error::Config("Collection service not available".to_string()))?;

        let mut existing_collection = service
            .get_collection(CollectionId(id.0 as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        // Merge the updates into the existing collection
        if let Some(name) = updates.get("name").and_then(|v| v.as_str()) {
            existing_collection.name = name.to_string();
        }
        if let Some(description) = updates.get("description") {
            existing_collection.description = if description.is_null() {
                None
            } else {
                description.as_str().map(|s| s.to_string())
            };
        }
        if let Some(parent_id) = updates.get("parent_id") {
            existing_collection.parent_id = if parent_id.is_null() {
                None
            } else {
                parent_id.as_i64().map(|id| id as i32)
            };
        }
        if let Some(color) = updates.get("color") {
            existing_collection.color = if color.is_null() {
                None
            } else {
                color.as_str().map(|s| s.to_string())
            };
        }
        if let Some(archived) = updates.get("archived").and_then(|v| v.as_bool()) {
            existing_collection.archived = Some(archived);
        }

        // Use ServiceManager for layered architecture
        service
            .update_collection(CollectionId(id.0 as i32), existing_collection)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Archives a collection (Metabase doesn't delete, only archives)
    pub async fn archive_collection(&self, id: MetabaseId) -> Result<Collection> {
        use crate::core::models::common::CollectionId;

        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to archive collection".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("collection", id.0);
            self.cache.invalidate(&cache_key);
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .collection_service()
            .ok_or_else(|| Error::Config("Collection service not available".to_string()))?
            .archive_collection(CollectionId(id.0 as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        // Get and return the updated collection
        self.get_collection(id).await
    }

    // ==================== Dashboard Operations ====================

    /// Gets a dashboard by ID
    pub async fn get_dashboard(&self, id: MetabaseId) -> Result<Dashboard> {
        use crate::core::models::common::DashboardId;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("dashboard", id.0);
            if let Some(dashboard) = self.cache.get_metadata::<Dashboard>(&cache_key) {
                return Ok(dashboard);
            }
        }

        // Use ServiceManager for layered architecture
        let dashboard = self
            .service_manager
            .dashboard_service()
            .ok_or_else(|| Error::Config("Dashboard service not available".to_string()))?
            .get_dashboard(DashboardId(id.0 as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("dashboard", id.0);
            let _ = self.cache.set_metadata(cache_key, &dashboard);
        }

        Ok(dashboard)
    }

    /// Lists all dashboards
    pub async fn list_dashboards(&self, pagination: Option<Pagination>) -> Result<Vec<Dashboard>> {
        use crate::repository::traits::PaginationParams;

        // Convert Pagination to PaginationParams if needed
        let pagination_params = pagination.map(|p| PaginationParams {
            page: None, // Using offset instead of page
            limit: Some(p.limit() as u32),
            offset: Some(p.offset() as u32),
        });

        // Use ServiceManager for layered architecture
        self.service_manager
            .dashboard_service()
            .ok_or_else(|| Error::Config("Dashboard service not available".to_string()))?
            .list_dashboards(pagination_params, None)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Creates a new dashboard
    pub async fn create_dashboard(&self, dashboard: Dashboard) -> Result<Dashboard> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to create dashboard".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture with validation
        self.service_manager
            .dashboard_service()
            .ok_or_else(|| Error::Config("Dashboard service not available".to_string()))?
            .create_dashboard(dashboard)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Updates an existing dashboard
    pub async fn update_dashboard(
        &self,
        id: MetabaseId,
        updates: serde_json::Value,
    ) -> Result<Dashboard> {
        use crate::core::models::common::DashboardId;

        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to update dashboard".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("dashboard", id.0);
            self.cache.invalidate(&cache_key);
        }

        // Convert JSON updates to Dashboard struct
        let dashboard: Dashboard = serde_json::from_value(updates)
            .map_err(|e| Error::Validation(format!("Invalid dashboard update: {}", e)))?;

        // Use ServiceManager for layered architecture with validation
        self.service_manager
            .dashboard_service()
            .ok_or_else(|| Error::Config("Dashboard service not available".to_string()))?
            .update_dashboard(DashboardId(id.0 as i32), dashboard)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Deletes a dashboard
    pub async fn delete_dashboard(&self, id: MetabaseId) -> Result<()> {
        use crate::core::models::common::DashboardId;

        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to delete dashboard".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("dashboard", id.0);
            self.cache.invalidate(&cache_key);
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .dashboard_service()
            .ok_or_else(|| Error::Config("Dashboard service not available".to_string()))?
            .delete_dashboard(DashboardId(id.0 as i32))
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Query Operations ====================

    /// Executes a dataset query
    pub async fn execute_query(&self, query: DatasetQuery) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_dataset_query(query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Executes a native SQL query
    pub async fn execute_native_query(
        &self,
        database: MetabaseId,
        native_query: NativeQuery,
    ) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute native query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_native_query(database.0 as i32, native_query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Extended Card Operations ====================

    /// Execute a card's query with optional parameters
    pub async fn execute_card_query(
        &self,
        card_id: i64,
        parameters: Option<Value>,
    ) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute card query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .execute_card_query(CardId(card_id as i32), parameters)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Export card query results in specified format
    pub async fn export_card_query(
        &self,
        card_id: i64,
        format: ExportFormat,
        parameters: Option<Value>,
    ) -> Result<Vec<u8>> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to export card query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .export_card_query(CardId(card_id as i32), format, parameters)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Execute a pivot query for a card
    pub async fn execute_card_pivot_query(
        &self,
        card_id: i64,
        parameters: Option<Value>,
    ) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute pivot query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .card_service()
            .ok_or_else(|| Error::Config("Card service not available".to_string()))?
            .execute_card_pivot_query(CardId(card_id as i32), parameters)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Database Metadata Operations ====================

    /// Get database metadata including tables and fields
    pub async fn get_database_metadata(&self, database_id: MetabaseId) -> Result<DatabaseMetadata> {
        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("database_metadata", database_id.0);
            if let Some(metadata) = self.cache.get_metadata::<DatabaseMetadata>(&cache_key) {
                return Ok(metadata);
            }
        }

        // Use ServiceManager for layered architecture
        let metadata = self
            .service_manager
            .database_service()
            .ok_or_else(|| Error::Config("Database service not available".to_string()))?
            .get_database_metadata(database_id)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))?;

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("database_metadata", database_id.0);
            let _ = self.cache.set_metadata(cache_key, &metadata);
        }

        Ok(metadata)
    }

    /// Sync database schema
    pub async fn sync_database_schema(&self, database_id: MetabaseId) -> Result<SyncResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to sync database schema".to_string(),
            ));
        }

        #[cfg(feature = "cache")]
        {
            let cache_key = cache_key("database_metadata", database_id.0);
            self.cache.invalidate(&cache_key);
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .database_service()
            .ok_or_else(|| Error::Config("Database service not available".to_string()))?
            .sync_database_schema(database_id)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Get all fields for a database
    pub async fn get_database_fields(&self, database_id: MetabaseId) -> Result<Vec<Field>> {
        // Use ServiceManager for layered architecture
        self.service_manager
            .database_service()
            .ok_or_else(|| Error::Config("Database service not available".to_string()))?
            .get_database_fields(database_id)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Get all schemas for a database
    pub async fn get_database_schemas(&self, database_id: MetabaseId) -> Result<Vec<String>> {
        // Use ServiceManager for layered architecture
        self.service_manager
            .database_service()
            .ok_or_else(|| Error::Config("Database service not available".to_string()))?
            .get_database_schemas(database_id)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== Dataset Operations ====================

    /// Execute a dataset query with advanced options
    pub async fn execute_dataset_query(&self, query: Value) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute dataset query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_raw_query(query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Execute a native query through the dataset endpoint
    pub async fn execute_dataset_native(&self, query: Value) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute native dataset query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_raw_query(query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Execute a pivot dataset query
    pub async fn execute_dataset_pivot(&self, query: Value) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute pivot dataset query".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_pivot_query(query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Export dataset query results
    pub async fn export_dataset(&self, format: ExportFormat, query: Value) -> Result<Vec<u8>> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to export dataset".to_string(),
            ));
        }

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .export_query(format.as_str(), query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== MBQL Query Operations ====================

    /// Execute an MBQL query
    #[cfg(feature = "query-builder")]
    pub async fn execute_mbql_query(
        &self,
        database_id: MetabaseId,
        query: MbqlQuery,
    ) -> Result<QueryResult> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to execute MBQL query".to_string(),
            ));
        }

        let dataset_query = query.to_dataset_query(database_id);

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .execute_dataset_query(dataset_query)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    /// Export MBQL query results in specified format
    #[cfg(feature = "query-builder")]
    pub async fn export_mbql_query(
        &self,
        database_id: MetabaseId,
        query: MbqlQuery,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to export MBQL query".to_string(),
            ));
        }

        let dataset_query = query.to_dataset_query(database_id);

        // Use ServiceManager for layered architecture
        // Convert dataset query to JSON Value for export
        let query_value = serde_json::to_value(&dataset_query)
            .map_err(|e| Error::Serialization(e.to_string()))?;

        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .export_query(format.as_str(), query_value)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }

    // ==================== SQL Convenience Methods ====================

    /// Execute a simple SQL query
    pub async fn execute_sql(&self, database_id: MetabaseId, sql: &str) -> Result<QueryResult> {
        let native_query = NativeQuery::new(sql);
        self.execute_native_query(database_id, native_query).await
    }

    /// Execute a parameterized SQL query
    pub async fn execute_sql_with_params(
        &self,
        database_id: MetabaseId,
        sql: &str,
        params: HashMap<String, Value>,
    ) -> Result<QueryResult> {
        let mut native_query = NativeQuery::new(sql);
        for (name, value) in params {
            native_query = native_query.with_param(&name, value);
        }
        self.execute_native_query(database_id, native_query).await
    }

    /// Export SQL query results in specified format
    pub async fn export_sql_query(
        &self,
        database_id: MetabaseId,
        sql: &str,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        if !self.is_authenticated() {
            return Err(Error::Authentication(
                "Authentication required to export SQL query".to_string(),
            ));
        }

        let native_query = NativeQuery::new(sql);
        let request = json!({
            "database": database_id.0,
            "type": "native",
            "native": {
                "query": native_query.query,
                "template-tags": native_query.template_tags
            }
        });

        // Use ServiceManager for layered architecture
        self.service_manager
            .query_service()
            .ok_or_else(|| Error::Config("Query service not available".to_string()))?
            .export_query(format.as_str(), request)
            .await
            .map_err(|e| Error::Config(format!("Service error: {}", e)))
    }
}