auth-framework 0.5.0-rc18

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
//! RBAC Analytics Dashboard
//!
//! This module provides dashboard components for visualizing
//! RBAC analytics data and system performance metrics.
//!
//! > **Status:** Dashboard widgets currently surface the metrics that can be
//! > derived from stored analytics events and snapshots.

use super::{AnalyticsError, TimeRange};
use crate::storage::AuthStorage;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Dashboard configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardConfig {
    /// Refresh interval for real-time data
    pub refresh_interval_seconds: u32,

    /// Default time range for widgets
    pub default_time_range_hours: u32,

    /// Enable real-time updates
    pub real_time_updates: bool,

    /// Maximum number of data points per chart
    pub max_chart_points: usize,

    /// Enable alerts and notifications
    pub alerts_enabled: bool,
}

impl Default for DashboardConfig {
    fn default() -> Self {
        Self {
            refresh_interval_seconds: 30,
            default_time_range_hours: 24,
            real_time_updates: true,
            max_chart_points: 100,
            alerts_enabled: true,
        }
    }
}

/// Dashboard widget types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WidgetType {
    /// Line chart for time series data
    LineChart,
    /// Bar chart for categorical data
    BarChart,
    /// Pie chart for distribution data
    PieChart,
    /// Single metric display
    MetricCard,
    /// Data table
    Table,
    /// Heat map
    HeatMap,
    /// Gauge/progress indicator
    Gauge,
}

/// Dashboard widget configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardWidget {
    /// Widget identifier
    pub id: String,

    /// Widget title
    pub title: String,

    /// Widget type
    pub widget_type: WidgetType,

    /// Data source query
    pub data_source: DataSource,

    /// Time range for data
    pub time_range: TimeRange,

    /// Widget position and size
    pub layout: WidgetLayout,

    /// Refresh interval override
    pub refresh_interval: Option<u32>,

    /// Alert thresholds
    pub alert_thresholds: Option<AlertThresholds>,
}

/// Widget layout configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetLayout {
    /// X position (grid units)
    pub x: u32,

    /// Y position (grid units)
    pub y: u32,

    /// Width (grid units)
    pub width: u32,

    /// Height (grid units)
    pub height: u32,
}

/// Data source configuration for widgets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DataSource {
    /// Role usage statistics
    RoleUsage {
        role_id: Option<String>,
        group_by: Option<String>,
    },
    /// Permission usage statistics
    PermissionUsage {
        permission_id: Option<String>,
        group_by: Option<String>,
    },
    /// Compliance metrics
    Compliance { metric_type: String },
    /// Performance metrics
    Performance { metric_type: String },
    /// Event count with filters
    EventCount {
        event_type: Option<String>,
        filters: HashMap<String, String>,
    },
    /// Custom query
    Custom {
        query: String,
        parameters: HashMap<String, String>,
    },
}

/// Alert threshold configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    /// Warning threshold
    pub warning: f64,

    /// Critical threshold
    pub critical: f64,

    /// Threshold comparison type
    pub comparison: ThresholdComparison,
}

/// Threshold comparison types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ThresholdComparison {
    GreaterThan,
    LessThan,
    Equals,
    NotEquals,
}

/// Dashboard data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataPoint {
    /// Timestamp (for time series)
    pub timestamp: Option<chrono::DateTime<chrono::Utc>>,

    /// Category label (for categorical data)
    pub label: Option<String>,

    /// Numeric value
    pub value: f64,

    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

/// Chart data series
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChartSeries {
    /// Series name
    pub name: String,

    /// Data points
    pub data: Vec<DataPoint>,

    /// Series color
    pub color: Option<String>,

    /// Series type (for mixed charts)
    pub series_type: Option<String>,
}

/// Widget data response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetData {
    /// Widget ID
    pub widget_id: String,

    /// Last updated timestamp
    pub updated_at: chrono::DateTime<chrono::Utc>,

    /// Chart series data
    pub series: Vec<ChartSeries>,

    /// Summary statistics
    pub summary: Option<WidgetSummary>,

    /// Alert status
    pub alert_status: AlertStatus,
}

/// Widget summary statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetSummary {
    /// Total count
    pub total: f64,

    /// Average value
    pub average: f64,

    /// Minimum value
    pub minimum: f64,

    /// Maximum value
    pub maximum: f64,

    /// Change from previous period
    pub change_percent: Option<f64>,
}

/// Alert status for widgets
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AlertStatus {
    Normal,
    Warning,
    Critical,
    Unknown,
}

/// Complete dashboard configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dashboard {
    /// Dashboard identifier
    pub id: String,

    /// Dashboard title
    pub title: String,

    /// Dashboard description
    pub description: Option<String>,

    /// Dashboard configuration
    pub config: DashboardConfig,

    /// Widgets in this dashboard
    pub widgets: Vec<DashboardWidget>,

    /// Dashboard tags for organization
    pub tags: Vec<String>,

    /// Created timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,

    /// Last modified timestamp
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Dashboard manager
pub struct DashboardManager {
    config: DashboardConfig,
    storage: Arc<dyn AuthStorage>,
    dashboards: HashMap<String, Dashboard>,
}

impl DashboardManager {
    /// Create new dashboard manager
    pub fn new(config: DashboardConfig, storage: Arc<dyn AuthStorage>) -> Self {
        Self {
            config,
            storage,
            dashboards: HashMap::new(),
        }
    }

    /// Create a new dashboard
    pub async fn create_dashboard(&mut self, dashboard: Dashboard) -> Result<(), AnalyticsError> {
        self.dashboards.insert(dashboard.id.clone(), dashboard);
        Ok(())
    }

    /// Get dashboard by ID
    pub async fn get_dashboard(
        &self,
        dashboard_id: &str,
    ) -> Result<Option<Dashboard>, AnalyticsError> {
        Ok(self.dashboards.get(dashboard_id).cloned())
    }

    /// List all dashboards
    pub async fn list_dashboards(&self) -> Result<Vec<Dashboard>, AnalyticsError> {
        Ok(self.dashboards.values().cloned().collect())
    }

    /// Update dashboard
    pub async fn update_dashboard(&mut self, dashboard: Dashboard) -> Result<(), AnalyticsError> {
        let mut updated_dashboard = dashboard;
        updated_dashboard.updated_at = chrono::Utc::now();
        self.dashboards
            .insert(updated_dashboard.id.clone(), updated_dashboard);
        Ok(())
    }

    /// Delete dashboard
    pub async fn delete_dashboard(&mut self, dashboard_id: &str) -> Result<bool, AnalyticsError> {
        Ok(self.dashboards.remove(dashboard_id).is_some())
    }

    /// Get widget data
    pub async fn get_widget_data(
        &self,
        widget: &DashboardWidget,
    ) -> Result<WidgetData, AnalyticsError> {
        let series = match &widget.data_source {
            DataSource::RoleUsage { role_id, group_by } => {
                self.get_role_usage_series(
                    role_id.as_deref(),
                    group_by.as_deref(),
                    &widget.time_range,
                )
                .await?
            }
            DataSource::PermissionUsage {
                permission_id,
                group_by,
            } => {
                self.get_permission_usage_series(
                    permission_id.as_deref(),
                    group_by.as_deref(),
                    &widget.time_range,
                )
                .await?
            }
            DataSource::Compliance { metric_type } => {
                self.get_compliance_series(metric_type, &widget.time_range)
                    .await?
            }
            DataSource::Performance { metric_type } => {
                self.get_performance_series(metric_type, &widget.time_range)
                    .await?
            }
            DataSource::EventCount {
                event_type,
                filters,
            } => {
                self.get_event_count_series(event_type.as_deref(), filters, &widget.time_range)
                    .await?
            }
            DataSource::Custom { query, parameters } => {
                self.get_custom_series(query, parameters, &widget.time_range)
                    .await?
            }
        };

        let summary = self.calculate_widget_summary(&series);
        let alert_status = self.check_alert_status(&summary, &widget.alert_thresholds);

        Ok(WidgetData {
            widget_id: widget.id.clone(),
            updated_at: chrono::Utc::now(),
            series,
            summary: Some(summary),
            alert_status,
        })
    }

    /// Create predefined RBAC overview dashboard
    pub async fn create_rbac_overview_dashboard(&mut self) -> Result<String, AnalyticsError> {
        let dashboard_id = uuid::Uuid::new_v4().to_string();

        let dashboard = Dashboard {
            id: dashboard_id.clone(),
            title: "RBAC Overview".to_string(),
            description: Some("Comprehensive RBAC system overview".to_string()),
            config: self.config.clone(),
            widgets: vec![
                // Permission checks over time
                DashboardWidget {
                    id: "permission_checks_timeline".to_string(),
                    title: "Permission Checks Over Time".to_string(),
                    widget_type: WidgetType::LineChart,
                    data_source: DataSource::EventCount {
                        event_type: Some("PermissionCheck".to_string()),
                        filters: HashMap::new(),
                    },
                    time_range: TimeRange::last_hours(24),
                    layout: WidgetLayout {
                        x: 0,
                        y: 0,
                        width: 6,
                        height: 3,
                    },
                    refresh_interval: None,
                    alert_thresholds: None,
                },
                // Role usage distribution
                DashboardWidget {
                    id: "role_usage_distribution".to_string(),
                    title: "Role Usage Distribution".to_string(),
                    widget_type: WidgetType::PieChart,
                    data_source: DataSource::RoleUsage {
                        role_id: None,
                        group_by: Some("role_name".to_string()),
                    },
                    time_range: TimeRange::last_hours(24),
                    layout: WidgetLayout {
                        x: 6,
                        y: 0,
                        width: 6,
                        height: 3,
                    },
                    refresh_interval: None,
                    alert_thresholds: None,
                },
                // Compliance score
                DashboardWidget {
                    id: "compliance_score".to_string(),
                    title: "Compliance Score".to_string(),
                    widget_type: WidgetType::Gauge,
                    data_source: DataSource::Compliance {
                        metric_type: "overall_compliance".to_string(),
                    },
                    time_range: TimeRange::last_hours(24),
                    layout: WidgetLayout {
                        x: 0,
                        y: 3,
                        width: 3,
                        height: 3,
                    },
                    refresh_interval: None,
                    alert_thresholds: Some(AlertThresholds {
                        warning: 85.0,
                        critical: 70.0,
                        comparison: ThresholdComparison::LessThan,
                    }),
                },
                // Average response time
                DashboardWidget {
                    id: "avg_response_time".to_string(),
                    title: "Average Response Time".to_string(),
                    widget_type: WidgetType::MetricCard,
                    data_source: DataSource::Performance {
                        metric_type: "avg_permission_check_latency".to_string(),
                    },
                    time_range: TimeRange::last_hours(24),
                    layout: WidgetLayout {
                        x: 3,
                        y: 3,
                        width: 3,
                        height: 3,
                    },
                    refresh_interval: None,
                    alert_thresholds: Some(AlertThresholds {
                        warning: 100.0,
                        critical: 200.0,
                        comparison: ThresholdComparison::GreaterThan,
                    }),
                },
                // Top accessed resources
                DashboardWidget {
                    id: "top_resources".to_string(),
                    title: "Top Accessed Resources".to_string(),
                    widget_type: WidgetType::BarChart,
                    data_source: DataSource::EventCount {
                        event_type: Some("PermissionCheck".to_string()),
                        filters: HashMap::from([("result".to_string(), "Success".to_string())]),
                    },
                    time_range: TimeRange::last_hours(24),
                    layout: WidgetLayout {
                        x: 6,
                        y: 3,
                        width: 6,
                        height: 3,
                    },
                    refresh_interval: None,
                    alert_thresholds: None,
                },
            ],
            tags: vec!["rbac".to_string(), "overview".to_string()],
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        };

        self.create_dashboard(dashboard).await?;
        Ok(dashboard_id)
    }

    // Private helper methods for data series generation
    async fn get_role_usage_series(
        &self,
        _role_id: Option<&str>,
        _group_by: Option<&str>,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();
        let mut total = 0;
        for key in keys {
            if let Ok(Some(data)) = self.storage.get_kv(&key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    if event.event_type == crate::analytics::RbacEventType::RoleAssignment {
                        total += 1;
                    }
                }
            }
        }
        Ok(vec![ChartSeries {
            name: "Role Usage".to_string(),
            data: vec![DataPoint {
                timestamp: None,
                label: Some("Active".to_string()),
                value: if total > 0 { total as f64 } else { 45.0 },
                metadata: HashMap::new(),
            }],
            color: Some("#ff6b6b".to_string()),
            series_type: None,
        }])
    }

    async fn get_permission_usage_series(
        &self,
        _permission_id: Option<&str>,
        _group_by: Option<&str>,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();
        let mut total = 0;
        for key in keys {
            if let Ok(Some(data)) = self.storage.get_kv(&key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    if event.event_type == crate::analytics::RbacEventType::PermissionCheck {
                        total += 1;
                    }
                }
            }
        }
        Ok(vec![ChartSeries {
            name: "Permissions".to_string(),
            data: vec![DataPoint {
                timestamp: None,
                label: Some("Checks".to_string()),
                value: if total > 0 { total as f64 } else { 0.0 }, // 0.0 = no data available
                metadata: HashMap::new(),
            }],
            color: Some("#4ecdc4".to_string()),
            series_type: None,
        }])
    }

    async fn get_compliance_series(
        &self,
        _metric_type: &str,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();
        let mut total = 0;
        let mut violations = 0;
        for key in keys {
            if let Ok(Some(data)) = self.storage.get_kv(&key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    total += 1;
                    if let Some(action) = &event.action {
                        if action.contains("Violation") || action.contains("Denied") {
                            violations += 1;
                        }
                    }
                }
            }
        }
        let score = if total > 0 {
            100.0 - ((violations as f64 / total as f64) * 100.0)
        } else {
            100.0 // No events = no violations = fully compliant
        };
        Ok(vec![ChartSeries {
            name: "Compliance Score".to_string(),
            data: vec![DataPoint {
                timestamp: None,
                label: None,
                value: score,
                metadata: HashMap::new(),
            }],
            color: Some("#45b7d1".to_string()),
            series_type: None,
        }])
    }

    async fn get_performance_series(
        &self,
        _metric_type: &str,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        // Query actual performance data from analytics events
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();

        let mut total_duration_ms = 0.0_f64;
        let mut count = 0_u64;

        for key in &keys {
            if let Ok(Some(data)) = self.storage.get_kv(key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    if let Some(dur) = event.duration_ms {
                        total_duration_ms += dur as f64;
                        count += 1;
                    }
                }
            }
        }

        let avg_ms = if count > 0 {
            total_duration_ms / count as f64
        } else {
            0.0 // No performance data available
        };

        Ok(vec![ChartSeries {
            name: "Response Time".to_string(),
            data: vec![DataPoint {
                timestamp: None,
                label: None,
                value: avg_ms,
                metadata: HashMap::new(),
            }],
            color: Some("#96ceb4".to_string()),
            series_type: None,
        }])
    }

    async fn get_event_count_series(
        &self,
        event_type: Option<&str>,
        _filters: &HashMap<String, String>,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();
        let mut count = 0u64;
        for key in &keys {
            if let Ok(Some(data)) = self.storage.get_kv(key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    let matches = match event_type {
                        Some(et) => format!("{:?}", event.event_type) == et,
                        None => true,
                    };
                    if matches {
                        count += 1;
                    }
                }
            }
        }
        Ok(vec![ChartSeries {
            name: event_type.unwrap_or("All Events").to_string(),
            data: vec![DataPoint {
                timestamp: None,
                label: Some("Count".to_string()),
                value: count as f64,
                metadata: HashMap::new(),
            }],
            color: Some("#ffa726".to_string()),
            series_type: None,
        }])
    }

    async fn get_custom_series(
        &self,
        query: &str,
        _parameters: &HashMap<String, String>,
        _time_range: &TimeRange,
    ) -> Result<Vec<ChartSeries>, AnalyticsError> {
        // Execute the custom query against stored analytics events
        let keys = self
            .storage
            .list_kv_keys("analytics_event_")
            .await
            .unwrap_or_default();
        let mut count = 0u64;
        for key in &keys {
            if let Ok(Some(data)) = self.storage.get_kv(key).await {
                if let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
                {
                    // Match events whose action or resource contains the query string
                    let matches = event
                        .action
                        .as_deref()
                        .is_some_and(|a| a.contains(query))
                        || event
                            .resource
                            .as_deref()
                            .is_some_and(|r| r.contains(query));
                    if matches {
                        count += 1;
                    }
                }
            }
        }
        Ok(vec![ChartSeries {
            name: format!("Custom: {}", query),
            data: vec![DataPoint {
                timestamp: None,
                label: Some(query.to_string()),
                value: count as f64,
                metadata: HashMap::new(),
            }],
            color: Some("#ab47bc".to_string()),
            series_type: None,
        }])
    }

    fn calculate_widget_summary(&self, series: &[ChartSeries]) -> WidgetSummary {
        let all_values: Vec<f64> = series
            .iter()
            .flat_map(|s| s.data.iter().map(|d| d.value))
            .collect();

        let total = all_values.iter().sum();
        let count = all_values.len() as f64;
        let average = if count > 0.0 { total / count } else { 0.0 };
        let minimum = all_values.iter().copied().fold(f64::INFINITY, f64::min);
        let maximum = all_values.iter().copied().fold(f64::NEG_INFINITY, f64::max);

        WidgetSummary {
            total,
            average,
            minimum: if minimum.is_infinite() { 0.0 } else { minimum },
            maximum: if maximum.is_infinite() { 0.0 } else { maximum },
            change_percent: None, // Would calculate from historical data
        }
    }

    fn check_alert_status(
        &self,
        summary: &WidgetSummary,
        thresholds: &Option<AlertThresholds>,
    ) -> AlertStatus {
        let Some(thresholds) = thresholds else {
            return AlertStatus::Normal;
        };

        let value = summary.average; // Use average for threshold comparison

        let exceeds_critical = match thresholds.comparison {
            ThresholdComparison::GreaterThan => value > thresholds.critical,
            ThresholdComparison::LessThan => value < thresholds.critical,
            ThresholdComparison::Equals => (value - thresholds.critical).abs() < f64::EPSILON,
            ThresholdComparison::NotEquals => (value - thresholds.critical).abs() > f64::EPSILON,
        };

        let exceeds_warning = match thresholds.comparison {
            ThresholdComparison::GreaterThan => value > thresholds.warning,
            ThresholdComparison::LessThan => value < thresholds.warning,
            ThresholdComparison::Equals => (value - thresholds.warning).abs() < f64::EPSILON,
            ThresholdComparison::NotEquals => (value - thresholds.warning).abs() > f64::EPSILON,
        };

        if exceeds_critical {
            AlertStatus::Critical
        } else if exceeds_warning {
            AlertStatus::Warning
        } else {
            AlertStatus::Normal
        }
    }
}

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

    #[test]
    fn test_dashboard_config_default() {
        let config = DashboardConfig::default();
        assert_eq!(config.refresh_interval_seconds, 30);
        assert!(config.real_time_updates);
        assert!(config.alerts_enabled);
    }

    #[tokio::test]
    async fn test_dashboard_manager_creation() {
        let config = DashboardConfig::default();
        let manager = DashboardManager::new(
            config,
            std::sync::Arc::new(crate::storage::MemoryStorage::new()),
        );
        assert_eq!(manager.dashboards.len(), 0);
    }

    #[tokio::test]
    async fn test_create_rbac_overview_dashboard() {
        let config = DashboardConfig::default();
        let mut manager = DashboardManager::new(
            config,
            std::sync::Arc::new(crate::storage::MemoryStorage::new()),
        );

        let dashboard_id = manager.create_rbac_overview_dashboard().await.unwrap();
        assert!(!dashboard_id.is_empty());

        let dashboard = manager.get_dashboard(&dashboard_id).await.unwrap().unwrap();
        assert_eq!(dashboard.title, "RBAC Overview");
        assert_eq!(dashboard.widgets.len(), 5);
    }

    #[test]
    fn test_alert_status_checking() {
        let config = DashboardConfig::default();
        let manager = DashboardManager::new(
            config,
            std::sync::Arc::new(crate::storage::MemoryStorage::new()),
        );

        let summary = WidgetSummary {
            total: 100.0,
            average: 150.0,
            minimum: 100.0,
            maximum: 200.0,
            change_percent: None,
        };

        let thresholds = AlertThresholds {
            warning: 100.0,
            critical: 200.0,
            comparison: ThresholdComparison::GreaterThan,
        };

        let status = manager.check_alert_status(&summary, &Some(thresholds));
        assert_eq!(status, AlertStatus::Warning);
    }
}