quetty-server 0.1.0

Core Azure Service Bus client library for Quetty terminal application
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
use super::{AzureAdConfig, ServiceBusError};
use crate::common::HttpError;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};

/// Azure Management API client for discovering Azure resources and managing Service Bus operations.
/// This client is used when authentication is done via Azure AD (device code flow).
const AZURE_MANAGEMENT_URL: &str = "https://management.azure.com";
const API_VERSION_SUBSCRIPTIONS: &str = "2022-12-01";
const API_VERSION_RESOURCE_GROUPS: &str = "2021-04-01";
const API_VERSION_SERVICE_BUS: &str = "2021-11-01";

#[derive(Debug, Clone)]
pub struct AzureManagementClient {
    client: reqwest::Client,
    /// Optional Azure AD configuration for operations that need persistent config
    azure_ad_config: Option<AzureAdConfig>,
}

// Resource discovery types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Subscription {
    pub id: String,
    #[serde(rename = "subscriptionId")]
    pub subscription_id: String,
    #[serde(rename = "displayName")]
    pub display_name: String,
    pub state: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResourceGroup {
    pub id: String,
    pub name: String,
    pub location: String,
    #[serde(default)]
    pub tags: std::collections::HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ServiceBusNamespace {
    pub id: String,
    pub name: String,
    pub location: String,
    #[serde(rename = "type")]
    pub resource_type: String,
    pub properties: NamespaceProperties,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NamespaceProperties {
    #[serde(rename = "serviceBusEndpoint")]
    pub service_bus_endpoint: String,
    pub status: Option<String>,
    #[serde(rename = "createdAt")]
    pub created_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AccessKeys {
    #[serde(rename = "primaryConnectionString")]
    pub primary_connection_string: String,
    #[serde(rename = "secondaryConnectionString")]
    pub secondary_connection_string: String,
    #[serde(rename = "primaryKey")]
    pub primary_key: String,
    #[serde(rename = "secondaryKey")]
    pub secondary_key: String,
}

// Queue statistics types
#[derive(Debug, Deserialize)]
struct QueuePropertiesResponse {
    properties: QueueProperties,
}

#[derive(Debug, Deserialize)]
struct QueueProperties {
    #[serde(rename = "countDetails")]
    count_details: CountDetails,
}

#[derive(Debug, Deserialize)]
struct CountDetails {
    #[serde(rename = "activeMessageCount")]
    active_message_count: i64,
    #[serde(rename = "deadLetterMessageCount")]
    dead_letter_message_count: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListResponse<T> {
    pub value: Vec<T>,
    #[serde(rename = "nextLink")]
    pub next_link: Option<String>,
}

impl AzureManagementClient {
    /// Create a new client for general operations (without persistent config)
    pub fn new(client: reqwest::Client) -> Self {
        Self {
            client,
            azure_ad_config: None,
        }
    }

    /// Create a new client with Azure AD configuration for authenticated operations
    pub fn with_config(client: reqwest::Client, azure_ad_config: AzureAdConfig) -> Self {
        Self {
            client,
            azure_ad_config: Some(azure_ad_config),
        }
    }

    /// Create a client from configuration (for backward compatibility)
    pub fn from_config(
        client: reqwest::Client,
        azure_ad_config: AzureAdConfig,
    ) -> Result<Self, ServiceBusError> {
        // Validate required fields when using from_config
        azure_ad_config.subscription_id()?;
        azure_ad_config.resource_group()?;
        azure_ad_config.namespace()?;

        Ok(Self::with_config(client, azure_ad_config))
    }

    /// Get access token from Azure AD config if available
    async fn get_management_api_token(&self) -> Result<String, ServiceBusError> {
        match &self.azure_ad_config {
            Some(config) => config
                .get_azure_ad_token(&self.client)
                .await
                .map_err(|e| ServiceBusError::AuthenticationError(e.to_string())),
            None => Err(ServiceBusError::ConfigurationError(
                "Azure AD configuration not available for this operation".to_string(),
            )),
        }
    }

    // ===== Resource Discovery Operations =====

    /// List all subscriptions accessible to the authenticated user
    pub async fn list_subscriptions(
        &self,
        token: &str,
    ) -> Result<Vec<Subscription>, ServiceBusError> {
        self.list_subscriptions_paginated(token, None)
            .await
            .map(|(subs, _)| subs)
    }

    /// List subscriptions with pagination support for large Azure environments
    async fn list_subscriptions_paginated(
        &self,
        token: &str,
        continuation_token: Option<String>,
    ) -> Result<(Vec<Subscription>, Option<String>), ServiceBusError> {
        let url = match continuation_token {
            Some(next_link) => next_link,
            None => format!(
                "{AZURE_MANAGEMENT_URL}/subscriptions?api-version={API_VERSION_SUBSCRIPTIONS}"
            ),
        };

        let client = self.client.clone();
        let token = token.to_string();
        let request = client
            .get(&url)
            .header(AUTHORIZATION, format!("Bearer {token}"));

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            return Err(ServiceBusError::from_azure_response(response, "list_subscriptions").await);
        }

        let list_response: ListResponse<Subscription> = response
            .json()
            .await
            .map_err(|e| ServiceBusError::ConfigurationError(e.to_string()))?;

        Ok((list_response.value, list_response.next_link))
    }

    /// List all subscriptions using automatic pagination for large environments
    pub async fn list_all_subscriptions(
        &self,
        token: &str,
    ) -> Result<Vec<Subscription>, ServiceBusError> {
        let mut all_subscriptions = Vec::new();
        let mut continuation_token = None;

        loop {
            let (mut page_subscriptions, next_token) = self
                .list_subscriptions_paginated(token, continuation_token)
                .await?;

            all_subscriptions.append(&mut page_subscriptions);

            match next_token {
                Some(token) => continuation_token = Some(token),
                None => break,
            }
        }

        Ok(all_subscriptions)
    }

    /// List all resource groups in a subscription
    pub async fn list_resource_groups(
        &self,
        token: &str,
        subscription_id: &str,
    ) -> Result<Vec<ResourceGroup>, ServiceBusError> {
        self.list_resource_groups_paginated(token, subscription_id, None)
            .await
            .map(|(groups, _)| groups)
    }

    /// List resource groups with pagination support for large Azure environments
    pub async fn list_resource_groups_paginated(
        &self,
        token: &str,
        subscription_id: &str,
        continuation_token: Option<String>,
    ) -> Result<(Vec<ResourceGroup>, Option<String>), ServiceBusError> {
        let url = match continuation_token {
            Some(next_link) => next_link,
            None => format!(
                "{AZURE_MANAGEMENT_URL}/subscriptions/{subscription_id}/resourcegroups?api-version={API_VERSION_RESOURCE_GROUPS}"
            ),
        };

        let request = self
            .client
            .get(&url)
            .header(AUTHORIZATION, format!("Bearer {token}"));

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            return Err(
                ServiceBusError::from_azure_response(response, "list_resource_groups").await,
            );
        }

        let list_response: ListResponse<ResourceGroup> = response
            .json()
            .await
            .map_err(|e| ServiceBusError::ConfigurationError(e.to_string()))?;

        Ok((list_response.value, list_response.next_link))
    }

    /// List all resource groups using automatic pagination for large environments
    pub async fn list_all_resource_groups(
        &self,
        token: &str,
        subscription_id: &str,
    ) -> Result<Vec<ResourceGroup>, ServiceBusError> {
        let mut all_groups = Vec::new();
        let mut continuation_token = None;

        loop {
            let (mut page_groups, next_token) = self
                .list_resource_groups_paginated(token, subscription_id, continuation_token)
                .await?;

            all_groups.append(&mut page_groups);

            match next_token {
                Some(token) => continuation_token = Some(token),
                None => break,
            }
        }

        Ok(all_groups)
    }

    /// List all Service Bus namespaces in a subscription
    pub async fn list_service_bus_namespaces(
        &self,
        token: &str,
        subscription_id: &str,
    ) -> Result<Vec<ServiceBusNamespace>, ServiceBusError> {
        self.list_service_bus_namespaces_paginated(token, subscription_id, None)
            .await
            .map(|(namespaces, _)| namespaces)
    }

    /// List Service Bus namespaces with pagination support for large Azure environments
    pub async fn list_service_bus_namespaces_paginated(
        &self,
        token: &str,
        subscription_id: &str,
        continuation_token: Option<String>,
    ) -> Result<(Vec<ServiceBusNamespace>, Option<String>), ServiceBusError> {
        let url = match continuation_token {
            Some(next_link) => next_link,
            None => format!(
                "{AZURE_MANAGEMENT_URL}/subscriptions/{subscription_id}/providers/Microsoft.ServiceBus/namespaces?api-version={API_VERSION_SERVICE_BUS}"
            ),
        };

        let request = self
            .client
            .get(&url)
            .header(AUTHORIZATION, format!("Bearer {token}"));

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            return Err(ServiceBusError::from_azure_response(
                response,
                "list_service_bus_namespaces",
            )
            .await);
        }

        let list_response: ListResponse<ServiceBusNamespace> = response
            .json()
            .await
            .map_err(|e| ServiceBusError::ConfigurationError(e.to_string()))?;

        Ok((list_response.value, list_response.next_link))
    }

    /// List all Service Bus namespaces using automatic pagination for large environments
    pub async fn list_all_service_bus_namespaces(
        &self,
        token: &str,
        subscription_id: &str,
    ) -> Result<Vec<ServiceBusNamespace>, ServiceBusError> {
        let mut all_namespaces = Vec::new();
        let mut continuation_token = None;

        loop {
            let (mut page_namespaces, next_token) = self
                .list_service_bus_namespaces_paginated(token, subscription_id, continuation_token)
                .await?;

            all_namespaces.append(&mut page_namespaces);

            match next_token {
                Some(token) => continuation_token = Some(token),
                None => break,
            }
        }

        Ok(all_namespaces)
    }

    /// Get the connection string for a Service Bus namespace
    pub async fn get_namespace_connection_string(
        &self,
        token: &str,
        subscription_id: &str,
        resource_group: &str,
        namespace: &str,
    ) -> Result<String, ServiceBusError> {
        // Try to get RootManageSharedAccessKey first
        let url = format!(
            "{AZURE_MANAGEMENT_URL}/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.ServiceBus/namespaces/{namespace}/authorizationRules/RootManageSharedAccessKey/listKeys?api-version={API_VERSION_SERVICE_BUS}"
        );

        let request = self
            .client
            .post(&url)
            .header(AUTHORIZATION, format!("Bearer {token}"))
            .header(CONTENT_TYPE, "application/json")
            .body("{}"); // Empty JSON body required for Azure Management API POST requests

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            return Err(ServiceBusError::from_azure_response(
                response,
                "get_namespace_connection_string",
            )
            .await);
        }

        let keys: AccessKeys = response
            .json()
            .await
            .map_err(|e| ServiceBusError::ConfigurationError(e.to_string()))?;

        Ok(keys.primary_connection_string)
    }

    /// List all queues in a Service Bus namespace
    pub async fn list_queues(
        &self,
        token: &str,
        subscription_id: &str,
        resource_group: &str,
        namespace: &str,
    ) -> Result<Vec<String>, ServiceBusError> {
        self.list_queues_paginated(token, subscription_id, resource_group, namespace, None)
            .await
            .map(|(queues, _)| queues)
    }

    /// List queues with pagination support for large Azure environments
    pub async fn list_queues_paginated(
        &self,
        token: &str,
        subscription_id: &str,
        resource_group: &str,
        namespace: &str,
        continuation_token: Option<String>,
    ) -> Result<(Vec<String>, Option<String>), ServiceBusError> {
        let url = match continuation_token {
            Some(next_link) => next_link,
            None => format!(
                "{AZURE_MANAGEMENT_URL}/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.ServiceBus/namespaces/{namespace}/queues?api-version={API_VERSION_SERVICE_BUS}"
            ),
        };

        let request = self
            .client
            .get(&url)
            .header(AUTHORIZATION, format!("Bearer {token}"));

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            return Err(ServiceBusError::from_azure_response(response, "list_queues").await);
        }

        let list_response: ListResponse<serde_json::Value> = response
            .json()
            .await
            .map_err(|e| ServiceBusError::ConfigurationError(e.to_string()))?;

        let queue_names: Vec<String> = list_response
            .value
            .iter()
            .filter_map(|queue| queue["name"].as_str().map(|s| s.to_string()))
            .collect();

        Ok((queue_names, list_response.next_link))
    }

    /// List all queues using automatic pagination for large environments
    pub async fn list_all_queues(
        &self,
        token: &str,
        subscription_id: &str,
        resource_group: &str,
        namespace: &str,
    ) -> Result<Vec<String>, ServiceBusError> {
        let mut all_queues = Vec::new();
        let mut continuation_token = None;

        loop {
            let (mut page_queues, next_token) = self
                .list_queues_paginated(
                    token,
                    subscription_id,
                    resource_group,
                    namespace,
                    continuation_token,
                )
                .await?;

            all_queues.append(&mut page_queues);

            match next_token {
                Some(token) => continuation_token = Some(token),
                None => break,
            }
        }

        Ok(all_queues)
    }

    // ===== Queue Statistics Operations =====

    /// Get the actual message count for a queue from Azure Management API
    pub async fn get_queue_message_count(&self, queue_name: &str) -> Result<u64, ServiceBusError> {
        let (active_count, _) = self.get_queue_counts(queue_name).await?;
        Ok(active_count)
    }

    /// Get both active and dead-letter counts from Azure Management API
    pub async fn get_queue_counts(&self, queue_name: &str) -> Result<(u64, u64), ServiceBusError> {
        self.get_queue_counts_with_retry(queue_name, 3).await
    }

    /// Get queue counts with retry logic for transient failures
    async fn get_queue_counts_with_retry(
        &self,
        queue_name: &str,
        max_retries: u32,
    ) -> Result<(u64, u64), ServiceBusError> {
        let mut last_error = None;

        for attempt in 0..=max_retries {
            match self.get_queue_counts_internal(queue_name).await {
                Ok(result) => return Ok(result),
                Err(e) => {
                    last_error = Some(e);

                    // Don't retry on authentication or configuration errors
                    if let Some(ref err) = last_error {
                        match err {
                            ServiceBusError::ConfigurationError(_)
                            | ServiceBusError::AuthenticationError(_) => {
                                log::debug!("Non-retryable error, failing immediately: {err}");
                                return Err(last_error.unwrap());
                            }
                            ServiceBusError::InternalError(msg) if msg.contains("404") => {
                                return Err(HttpError::InvalidResponse {
                                    expected: "2xx status".to_string(),
                                    actual: format!("Queue not found: {queue_name}"),
                                }
                                .into());
                            }
                            _ => {}
                        }
                    }

                    if attempt < max_retries {
                        let delay = Duration::from_millis(100 * (2_u64.pow(attempt))); // Exponential backoff
                        log::debug!(
                            "Attempt {} failed, retrying in {:?}: {}",
                            attempt + 1,
                            delay,
                            last_error.as_ref().unwrap()
                        );
                        tokio::time::sleep(delay).await;
                    }
                }
            }
        }

        Err(last_error.unwrap())
    }

    /// Internal implementation for getting queue counts (single attempt)
    async fn get_queue_counts_internal(
        &self,
        queue_name: &str,
    ) -> Result<(u64, u64), ServiceBusError> {
        log::debug!("Getting queue counts for: {queue_name}");

        // Get configuration from Azure AD config
        let config = self.azure_ad_config.as_ref().ok_or_else(|| {
            ServiceBusError::ConfigurationError(
                "Azure AD configuration required for queue statistics".to_string(),
            )
        })?;

        let subscription_id = config.subscription_id()?;
        let resource_group = config.resource_group()?;
        let namespace = config.namespace()?;

        // Get access token
        let access_token = self.get_management_api_token().await?;

        // Build the management API URL with encoded queue name
        let encoded_queue_name = urlencoding::encode(queue_name);
        let url = format!(
            "{AZURE_MANAGEMENT_URL}/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.ServiceBus/namespaces/{namespace}/queues/{encoded_queue_name}?api-version={API_VERSION_SERVICE_BUS}"
        );

        log::debug!("Requesting queue properties from Azure Management API: {url}");

        let request = self
            .client
            .get(&url)
            .header(AUTHORIZATION, format!("Bearer {access_token}"))
            .header(CONTENT_TYPE, "application/json");

        let response = request
            .send()
            .await
            .map_err(|e| ServiceBusError::ConnectionFailed(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();

            if status == 404 {
                return Err(ServiceBusError::azure_api_error(
                    "get_queue_counts",
                    "QueueNotFound",
                    404,
                    format!("Queue not found: {queue_name}"),
                ));
            }

            return Err(ServiceBusError::from_azure_response(response, "get_queue_counts").await);
        }

        let response_text = response
            .text()
            .await
            .map_err(|e| ServiceBusError::InternalError(format!("Failed to read response: {e}")))?;

        let queue_response: QueuePropertiesResponse = serde_json::from_str(&response_text)
            .map_err(|e| {
                ServiceBusError::ConfigurationError(format!("Failed to parse JSON: {e}"))
            })?;

        let active_raw = queue_response.properties.count_details.active_message_count;
        let dlq_raw = queue_response
            .properties
            .count_details
            .dead_letter_message_count;

        let active = if active_raw < 0 { 0 } else { active_raw as u64 };
        let dlq = if dlq_raw < 0 { 0 } else { dlq_raw as u64 };

        Ok((active, dlq))
    }
}

/// Cache entry with TTL tracking
#[derive(Debug, Clone)]
struct CacheEntry<T> {
    data: T,
    cached_at: Instant,
}

impl<T> CacheEntry<T> {
    fn new(data: T) -> Self {
        Self {
            data,
            cached_at: Instant::now(),
        }
    }

    fn is_expired(&self, ttl: Duration) -> bool {
        self.cached_at.elapsed() > ttl
    }
}

/// Cache for Azure resources to avoid repeated API calls
#[derive(Debug, Clone)]
pub struct AzureResourceCache {
    subscriptions: Option<CacheEntry<Vec<Subscription>>>,
    resource_groups: std::collections::HashMap<String, CacheEntry<Vec<ResourceGroup>>>,
    namespaces: std::collections::HashMap<String, CacheEntry<Vec<ServiceBusNamespace>>>,
    connection_strings: std::collections::HashMap<String, CacheEntry<String>>,
    cache_ttl: Duration,
    max_entries_per_cache: usize,
}

impl AzureResourceCache {
    pub fn new() -> Self {
        Self::with_config(Duration::from_secs(300), 100) // 5 minutes TTL, 100 entries max
    }

    pub fn with_config(cache_ttl: Duration, max_entries: usize) -> Self {
        Self {
            subscriptions: None,
            resource_groups: std::collections::HashMap::new(),
            namespaces: std::collections::HashMap::new(),
            connection_strings: std::collections::HashMap::new(),
            cache_ttl,
            max_entries_per_cache: max_entries,
        }
    }

    pub fn cache_subscriptions(&mut self, subscriptions: Vec<Subscription>) {
        self.subscriptions = Some(CacheEntry::new(subscriptions));
    }

    pub fn cache_resource_groups(&mut self, subscription_id: String, groups: Vec<ResourceGroup>) {
        // Enforce size limit using LRU eviction
        if self.resource_groups.len() >= self.max_entries_per_cache
            && !self.resource_groups.contains_key(&subscription_id)
        {
            // Remove oldest entry
            if let Some(oldest_key) = self.find_oldest_entry(&self.resource_groups) {
                self.resource_groups.remove(&oldest_key);
            }
        }
        self.resource_groups
            .insert(subscription_id, CacheEntry::new(groups));
    }

    pub fn cache_namespaces(
        &mut self,
        subscription_id: String,
        namespaces: Vec<ServiceBusNamespace>,
    ) {
        // Enforce size limit using LRU eviction
        if self.namespaces.len() >= self.max_entries_per_cache
            && !self.namespaces.contains_key(&subscription_id)
        {
            // Remove oldest entry
            if let Some(oldest_key) = self.find_oldest_entry(&self.namespaces) {
                self.namespaces.remove(&oldest_key);
            }
        }
        self.namespaces
            .insert(subscription_id, CacheEntry::new(namespaces));
    }

    pub fn cache_connection_string(&mut self, namespace_id: String, connection_string: String) {
        // Enforce size limit using LRU eviction
        if self.connection_strings.len() >= self.max_entries_per_cache
            && !self.connection_strings.contains_key(&namespace_id)
        {
            // Remove oldest entry
            if let Some(oldest_key) = self.find_oldest_entry(&self.connection_strings) {
                self.connection_strings.remove(&oldest_key);
            }
        }
        self.connection_strings
            .insert(namespace_id, CacheEntry::new(connection_string));
    }

    pub fn get_cached_connection_string(&self, namespace_id: &str) -> Option<String> {
        self.connection_strings
            .get(namespace_id)
            .filter(|entry| !entry.is_expired(self.cache_ttl))
            .map(|entry| entry.data.clone())
    }

    /// Get cached subscriptions if available
    pub fn get_cached_subscriptions(&self) -> Option<Vec<Subscription>> {
        self.subscriptions
            .as_ref()
            .filter(|entry| !entry.is_expired(self.cache_ttl))
            .map(|entry| entry.data.clone())
    }

    /// Get cached resource groups for a subscription
    pub fn get_cached_resource_groups(&self, subscription_id: &str) -> Option<Vec<ResourceGroup>> {
        self.resource_groups
            .get(subscription_id)
            .filter(|entry| !entry.is_expired(self.cache_ttl))
            .map(|entry| entry.data.clone())
    }

    /// Get cached namespaces for a subscription
    pub fn get_cached_namespaces(&self, subscription_id: &str) -> Option<Vec<ServiceBusNamespace>> {
        self.namespaces
            .get(subscription_id)
            .filter(|entry| !entry.is_expired(self.cache_ttl))
            .map(|entry| entry.data.clone())
    }

    /// Check if cache is empty (no resources cached)
    pub fn is_empty(&self) -> bool {
        self.subscriptions.is_none()
            && self.resource_groups.is_empty()
            && self.namespaces.is_empty()
            && self.connection_strings.is_empty()
    }

    /// Clear all cached data
    pub fn clear(&mut self) {
        self.subscriptions = None;
        self.resource_groups.clear();
        self.namespaces.clear();
        self.connection_strings.clear();
    }

    /// Remove expired entries from all caches
    pub fn clean_expired(&mut self) {
        // Clean subscriptions
        if let Some(ref entry) = self.subscriptions {
            if entry.is_expired(self.cache_ttl) {
                self.subscriptions = None;
            }
        }

        // Clean resource groups
        self.resource_groups
            .retain(|_, entry| !entry.is_expired(self.cache_ttl));

        // Clean namespaces
        self.namespaces
            .retain(|_, entry| !entry.is_expired(self.cache_ttl));

        // Clean connection strings
        self.connection_strings
            .retain(|_, entry| !entry.is_expired(self.cache_ttl));
    }

    /// Find the oldest entry in a cache map for LRU eviction
    fn find_oldest_entry<T>(
        &self,
        cache: &std::collections::HashMap<String, CacheEntry<T>>,
    ) -> Option<String> {
        cache
            .iter()
            .min_by_key(|(_, entry)| entry.cached_at)
            .map(|(key, _)| key.clone())
    }
}

impl Default for AzureResourceCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for queue statistics
#[derive(Debug, Clone)]
pub struct StatisticsConfig {
    pub display_enabled: bool,
    pub cache_ttl_seconds: u64,
    pub use_management_api: bool,
}

impl StatisticsConfig {
    pub fn new(display_enabled: bool, cache_ttl_seconds: u64, use_management_api: bool) -> Self {
        Self {
            display_enabled,
            cache_ttl_seconds,
            use_management_api,
        }
    }
}