oxirs-stream 0.4.1

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

use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};
use uuid::Uuid;

/// Enterprise audit logger configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnterpriseAuditConfig {
    /// Enable audit logging
    pub enabled: bool,
    /// Audit log storage backend
    pub storage: AuditStorageConfig,
    /// Event filtering configuration
    pub filtering: AuditFilterConfig,
    /// Retention policy
    pub retention: AuditRetentionConfig,
    /// Compliance configuration
    pub compliance: ComplianceConfig,
    /// Encryption configuration for audit logs
    pub encryption: AuditEncryptionConfig,
    /// Real-time streaming of audit events
    pub streaming: AuditStreamingConfig,
}

impl Default for EnterpriseAuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            storage: AuditStorageConfig::default(),
            filtering: AuditFilterConfig::default(),
            retention: AuditRetentionConfig::default(),
            compliance: ComplianceConfig::default(),
            encryption: AuditEncryptionConfig::default(),
            streaming: AuditStreamingConfig::default(),
        }
    }
}

/// Audit log storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditStorageConfig {
    /// Storage backend type
    pub backend: AuditStorageBackend,
    /// File storage path (for file backend)
    pub file_path: Option<PathBuf>,
    /// Database connection string (for database backend)
    pub database_url: Option<String>,
    /// S3 bucket configuration (for S3 backend)
    pub s3_config: Option<S3AuditConfig>,
    /// Buffer size for batching
    pub buffer_size: usize,
    /// Flush interval in seconds
    pub flush_interval_secs: u64,
}

impl Default for AuditStorageConfig {
    fn default() -> Self {
        Self {
            backend: AuditStorageBackend::File,
            file_path: Some(PathBuf::from("/var/log/oxirs/audit.jsonl")),
            database_url: None,
            s3_config: None,
            buffer_size: 1000,
            flush_interval_secs: 60,
        }
    }
}

/// Audit storage backend types
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuditStorageBackend {
    /// File-based storage (JSONL format)
    File,
    /// Database storage (PostgreSQL, MySQL)
    Database,
    /// S3-compatible object storage
    S3,
    /// Elasticsearch
    Elasticsearch,
    /// Splunk
    Splunk,
    /// Custom backend
    Custom,
}

/// S3 audit storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct S3AuditConfig {
    /// S3 bucket name
    pub bucket: String,
    /// S3 region
    pub region: String,
    /// S3 prefix for audit logs
    pub prefix: String,
    /// AWS access key ID
    pub access_key_id: Option<String>,
    /// AWS secret access key
    pub secret_access_key: Option<String>,
    /// Server-side encryption
    pub server_side_encryption: bool,
}

/// Audit event filtering configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditFilterConfig {
    /// Minimum severity level to log
    pub min_severity: AuditSeverity,
    /// Event types to include
    pub include_event_types: Vec<AuditEventType>,
    /// Event types to exclude
    pub exclude_event_types: Vec<AuditEventType>,
    /// User IDs to exclude from auditing (e.g., system users)
    pub exclude_users: Vec<String>,
    /// Resource patterns to exclude
    pub exclude_resources: Vec<String>,
}

impl Default for AuditFilterConfig {
    fn default() -> Self {
        Self {
            min_severity: AuditSeverity::Info,
            include_event_types: vec![],
            exclude_event_types: vec![],
            exclude_users: vec![],
            exclude_resources: vec![],
        }
    }
}

/// Audit retention policy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditRetentionConfig {
    /// Retention period in days
    pub retention_days: u32,
    /// Archive old logs
    pub archive_enabled: bool,
    /// Archive destination
    pub archive_destination: Option<String>,
    /// Compression for archived logs
    pub archive_compression: CompressionType,
    /// Automatic cleanup of expired logs
    pub auto_cleanup: bool,
}

impl Default for AuditRetentionConfig {
    fn default() -> Self {
        Self {
            retention_days: 365, // 1 year default
            archive_enabled: true,
            archive_destination: None,
            archive_compression: CompressionType::Gzip,
            auto_cleanup: true,
        }
    }
}

/// Compression types for audit logs
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum CompressionType {
    None,
    Gzip,
    Zstd,
    Bzip2,
}

/// Compliance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceConfig {
    /// Compliance standards to adhere to
    pub standards: Vec<ComplianceStandard>,
    /// Enable compliance reporting
    pub reporting_enabled: bool,
    /// Report generation interval in days
    pub report_interval_days: u32,
    /// Report destination
    pub report_destination: Option<String>,
}

impl Default for ComplianceConfig {
    fn default() -> Self {
        Self {
            standards: vec![ComplianceStandard::SOC2],
            reporting_enabled: true,
            report_interval_days: 30,
            report_destination: None,
        }
    }
}

/// Compliance standards
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ComplianceStandard {
    /// GDPR (General Data Protection Regulation)
    GDPR,
    /// HIPAA (Health Insurance Portability and Accountability Act)
    HIPAA,
    /// SOC 2 (Service Organization Control 2)
    SOC2,
    /// PCI DSS (Payment Card Industry Data Security Standard)
    PCIDSS,
    /// ISO 27001
    ISO27001,
}

impl fmt::Display for ComplianceStandard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ComplianceStandard::GDPR => write!(f, "GDPR"),
            ComplianceStandard::HIPAA => write!(f, "HIPAA"),
            ComplianceStandard::SOC2 => write!(f, "SOC2"),
            ComplianceStandard::PCIDSS => write!(f, "PCI-DSS"),
            ComplianceStandard::ISO27001 => write!(f, "ISO 27001"),
        }
    }
}

/// Audit log encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEncryptionConfig {
    /// Enable encryption for audit logs
    pub enabled: bool,
    /// Encryption algorithm
    pub algorithm: EncryptionAlgorithm,
    /// Key management system
    pub key_management: KeyManagementConfig,
}

impl Default for AuditEncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            algorithm: EncryptionAlgorithm::AES256GCM,
            key_management: KeyManagementConfig::default(),
        }
    }
}

/// Encryption algorithms for audit logs
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum EncryptionAlgorithm {
    AES256GCM,
    ChaCha20Poly1305,
    AES256CBC,
}

/// Key management configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyManagementConfig {
    /// Key management system type
    pub kms_type: KmsType,
    /// KMS endpoint URL
    pub kms_url: Option<String>,
    /// Key rotation interval in days
    pub rotation_interval_days: u32,
}

impl Default for KeyManagementConfig {
    fn default() -> Self {
        Self {
            kms_type: KmsType::Local,
            kms_url: None,
            rotation_interval_days: 90,
        }
    }
}

/// Key management system types
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum KmsType {
    /// Local key storage (for development)
    Local,
    /// AWS KMS
    AwsKms,
    /// Azure Key Vault
    AzureKeyVault,
    /// Google Cloud KMS
    GcpKms,
    /// HashiCorp Vault
    HashiCorpVault,
}

/// Audit streaming configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AuditStreamingConfig {
    /// Enable real-time streaming of audit events
    pub enabled: bool,
    /// Streaming destinations
    pub destinations: Vec<StreamingDestination>,
}

/// Streaming destination configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingDestination {
    /// Destination type
    pub destination_type: DestinationType,
    /// Destination endpoint URL
    pub endpoint: String,
    /// Authentication configuration
    pub auth: Option<DestinationAuth>,
}

/// Destination types for audit streaming
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum DestinationType {
    Kafka,
    Kinesis,
    Webhook,
    SIEM,
}

/// Authentication for streaming destinations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DestinationAuth {
    pub auth_type: AuthType,
    pub credentials: HashMap<String, String>,
}

/// Authentication types
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthType {
    ApiKey,
    OAuth2,
    Basic,
    Certificate,
}

/// Audit event types
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum AuditEventType {
    /// Authentication events
    Authentication,
    /// Authorization events
    Authorization,
    /// Data access events
    DataAccess,
    /// Data modification events
    DataModification,
    /// Configuration changes
    ConfigurationChange,
    /// Security events
    Security,
    /// System events
    System,
    /// Administrative actions
    Administrative,
    /// Compliance events
    Compliance,
}

impl fmt::Display for AuditEventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuditEventType::Authentication => write!(f, "Authentication"),
            AuditEventType::Authorization => write!(f, "Authorization"),
            AuditEventType::DataAccess => write!(f, "DataAccess"),
            AuditEventType::DataModification => write!(f, "DataModification"),
            AuditEventType::ConfigurationChange => write!(f, "ConfigurationChange"),
            AuditEventType::Security => write!(f, "Security"),
            AuditEventType::System => write!(f, "System"),
            AuditEventType::Administrative => write!(f, "Administrative"),
            AuditEventType::Compliance => write!(f, "Compliance"),
        }
    }
}

/// Audit severity levels
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum AuditSeverity {
    Debug,
    Info,
    Warning,
    Error,
    Critical,
}

impl fmt::Display for AuditSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuditSeverity::Debug => write!(f, "DEBUG"),
            AuditSeverity::Info => write!(f, "INFO"),
            AuditSeverity::Warning => write!(f, "WARNING"),
            AuditSeverity::Error => write!(f, "ERROR"),
            AuditSeverity::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Enterprise audit event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnterpriseAuditEvent {
    /// Unique event ID
    pub event_id: String,
    /// Event timestamp
    pub timestamp: DateTime<Utc>,
    /// Event type
    pub event_type: AuditEventType,
    /// Severity level
    pub severity: AuditSeverity,
    /// User who triggered the event
    pub user_id: Option<String>,
    /// User's IP address
    pub source_ip: Option<String>,
    /// Resource being accessed/modified
    pub resource: String,
    /// Action performed
    pub action: String,
    /// Result of the action
    pub result: ActionResult,
    /// Additional details
    pub details: HashMap<String, serde_json::Value>,
    /// Compliance tags
    pub compliance_tags: Vec<ComplianceStandard>,
    /// Session ID
    pub session_id: Option<String>,
    /// Request ID
    pub request_id: Option<String>,
    /// Correlation ID for distributed tracing
    pub correlation_id: Option<String>,
}

/// Action result
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ActionResult {
    Success,
    Failure,
    PartialSuccess,
    Denied,
}

impl fmt::Display for ActionResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ActionResult::Success => write!(f, "SUCCESS"),
            ActionResult::Failure => write!(f, "FAILURE"),
            ActionResult::PartialSuccess => write!(f, "PARTIAL_SUCCESS"),
            ActionResult::Denied => write!(f, "DENIED"),
        }
    }
}

/// Enterprise audit logger
pub struct EnterpriseAuditLogger {
    config: EnterpriseAuditConfig,
    buffer: Arc<RwLock<Vec<EnterpriseAuditEvent>>>,
    metrics: Arc<RwLock<AuditMetrics>>,
}

/// Audit metrics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditMetrics {
    /// Total events logged
    pub events_total: u64,
    /// Events by type
    pub events_by_type: HashMap<String, u64>,
    /// Events by severity
    pub events_by_severity: HashMap<String, u64>,
    /// Events by result
    pub events_by_result: HashMap<String, u64>,
    /// Failed to log events
    pub events_failed: u64,
    /// Buffer flushes
    pub buffer_flushes: u64,
    /// Last flush timestamp
    pub last_flush: Option<DateTime<Utc>>,
}

impl EnterpriseAuditLogger {
    /// Create a new enterprise audit logger
    pub fn new(config: EnterpriseAuditConfig) -> Self {
        Self {
            config,
            buffer: Arc::new(RwLock::new(Vec::new())),
            metrics: Arc::new(RwLock::new(AuditMetrics::default())),
        }
    }

    /// Initialize the audit logger
    pub async fn initialize(&self) -> Result<()> {
        if !self.config.enabled {
            info!("Enterprise audit logging is disabled");
            return Ok(());
        }

        info!("Initializing enterprise audit logger");

        // Initialize storage backend
        self.initialize_storage().await?;

        // Start background flusher
        self.start_background_flusher().await?;

        // Initialize streaming if enabled
        if self.config.streaming.enabled {
            self.initialize_streaming().await?;
        }

        info!("Enterprise audit logger initialized successfully");
        Ok(())
    }

    /// Initialize storage backend
    async fn initialize_storage(&self) -> Result<()> {
        match self.config.storage.backend {
            AuditStorageBackend::File => {
                if let Some(path) = &self.config.storage.file_path {
                    // Ensure directory exists
                    if let Some(parent) = path.parent() {
                        tokio::fs::create_dir_all(parent).await?;
                    }
                    debug!("File storage initialized: {:?}", path);
                }
            }
            AuditStorageBackend::Database => {
                debug!("Database storage initialization (placeholder)");
            }
            AuditStorageBackend::S3 => {
                debug!("S3 storage initialization (placeholder)");
            }
            AuditStorageBackend::Elasticsearch => {
                debug!("Elasticsearch storage initialization (placeholder)");
            }
            AuditStorageBackend::Splunk => {
                debug!("Splunk storage initialization (placeholder)");
            }
            AuditStorageBackend::Custom => {
                debug!("Custom storage initialization (placeholder)");
            }
        }

        Ok(())
    }

    /// Start background flusher task
    async fn start_background_flusher(&self) -> Result<()> {
        debug!("Starting background audit log flusher");
        // In a real implementation, this would spawn a tokio task
        // that periodically flushes the buffer to storage
        Ok(())
    }

    /// Initialize streaming destinations
    async fn initialize_streaming(&self) -> Result<()> {
        debug!("Initializing audit event streaming");
        for destination in &self.config.streaming.destinations {
            debug!(
                "Setting up streaming to {:?}: {}",
                destination.destination_type, destination.endpoint
            );
        }
        Ok(())
    }

    /// Log an audit event
    pub async fn log_event(&self, event: EnterpriseAuditEvent) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        // Apply filtering
        if !self.should_log_event(&event).await {
            return Ok(());
        }

        // Add to buffer
        {
            let mut buffer = self.buffer.write().await;
            buffer.push(event.clone());

            // Check if buffer needs flushing
            if buffer.len() >= self.config.storage.buffer_size {
                drop(buffer);
                self.flush_buffer().await?;
            }
        }

        // Update metrics
        {
            let mut metrics = self.metrics.write().await;
            metrics.events_total += 1;
            *metrics
                .events_by_type
                .entry(event.event_type.to_string())
                .or_insert(0) += 1;
            *metrics
                .events_by_severity
                .entry(event.severity.to_string())
                .or_insert(0) += 1;
            *metrics
                .events_by_result
                .entry(event.result.to_string())
                .or_insert(0) += 1;
        }

        // Stream event if enabled
        if self.config.streaming.enabled {
            self.stream_event(&event).await?;
        }

        Ok(())
    }

    /// Check if event should be logged based on filters
    async fn should_log_event(&self, event: &EnterpriseAuditEvent) -> bool {
        // Check severity level
        if event.severity < self.config.filtering.min_severity {
            return false;
        }

        // Check excluded event types
        if self
            .config
            .filtering
            .exclude_event_types
            .contains(&event.event_type)
        {
            return false;
        }

        // Check include list (if not empty)
        if !self.config.filtering.include_event_types.is_empty()
            && !self
                .config
                .filtering
                .include_event_types
                .contains(&event.event_type)
        {
            return false;
        }

        // Check excluded users
        if let Some(user_id) = &event.user_id {
            if self.config.filtering.exclude_users.contains(user_id) {
                return false;
            }
        }

        true
    }

    /// Flush buffer to storage
    pub async fn flush_buffer(&self) -> Result<()> {
        let events = {
            let mut buffer = self.buffer.write().await;
            if buffer.is_empty() {
                return Ok(());
            }
            std::mem::take(&mut *buffer)
        };

        debug!("Flushing {} audit events to storage", events.len());

        // Write to storage. If the write fails, restore the taken events to the
        // front of the buffer so the audit trail is not silently discarded and a
        // subsequent flush can retry.
        if let Err(e) = self.write_to_storage(&events).await {
            let mut buffer = self.buffer.write().await;
            let mut restored = events;
            restored.append(&mut buffer);
            *buffer = restored;
            return Err(e);
        }

        // Update metrics
        {
            let mut metrics = self.metrics.write().await;
            metrics.buffer_flushes += 1;
            metrics.last_flush = Some(Utc::now());
        }

        Ok(())
    }

    /// Write events to storage.
    ///
    /// The file backend performs a real appending JSONL write. Backends that are
    /// not yet implemented return an explicit error (fail-loud) rather than
    /// silently succeeding, so callers never believe an audit trail was
    /// persisted when it was not.
    async fn write_to_storage(&self, events: &[EnterpriseAuditEvent]) -> Result<()> {
        match self.config.storage.backend {
            AuditStorageBackend::File => {
                let path = self.config.storage.file_path.as_ref().ok_or_else(|| {
                    anyhow::anyhow!(
                        "Audit File storage backend selected but no file_path configured"
                    )
                })?;

                let mut content = String::new();
                for event in events {
                    let json = serde_json::to_string(event)?;
                    content.push_str(&json);
                    content.push('\n');
                }

                if let Some(parent) = path.parent() {
                    if !parent.as_os_str().is_empty() {
                        tokio::fs::create_dir_all(parent).await?;
                    }
                }

                use tokio::io::AsyncWriteExt;
                let mut file = tokio::fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(path)
                    .await?;
                file.write_all(content.as_bytes()).await?;
                file.flush().await?;

                debug!("Wrote {} bytes to audit log {:?}", content.len(), path);
                Ok(())
            }
            other => Err(anyhow::anyhow!(
                "Audit storage backend {:?} is not implemented; cannot persist {} event(s)",
                other,
                events.len()
            )),
        }
    }

    /// Stream event to real-time destinations
    async fn stream_event(&self, event: &EnterpriseAuditEvent) -> Result<()> {
        for destination in &self.config.streaming.destinations {
            debug!(
                "Streaming event {} to {:?}",
                event.event_id, destination.destination_type
            );
            // In a real implementation, send to actual destination
        }
        Ok(())
    }

    /// Get audit metrics
    pub async fn get_metrics(&self) -> AuditMetrics {
        self.metrics.read().await.clone()
    }

    /// Generate compliance report
    pub async fn generate_compliance_report(
        &self,
        standard: ComplianceStandard,
        start_date: DateTime<Utc>,
        end_date: DateTime<Utc>,
    ) -> Result<ComplianceReport> {
        info!(
            "Generating compliance report for {} from {} to {}",
            standard, start_date, end_date
        );

        // Query the persisted audit trail for events in range that carry this
        // standard's compliance tag, then compute real totals and findings.
        let events = self.query_events(start_date, end_date, standard).await?;
        let total_events = events.len() as u64;

        let mut findings = Vec::new();
        for event in &events {
            let finding = match event.result {
                ActionResult::Denied => Some((
                    FindingType::NonCompliance,
                    format!("Denied {} on resource '{}'", event.action, event.resource),
                    Some(
                        "Review access control policy and verify the denial was expected"
                            .to_string(),
                    ),
                )),
                ActionResult::Failure => Some((
                    FindingType::Warning,
                    format!("Failed {} on resource '{}'", event.action, event.resource),
                    Some(
                        "Investigate the failure and confirm no data integrity impact".to_string(),
                    ),
                )),
                _ => None,
            };

            if let Some((finding_type, description, remediation)) = finding {
                findings.push(ComplianceFinding {
                    finding_id: Uuid::new_v4().to_string(),
                    finding_type,
                    severity: event.severity,
                    description,
                    affected_events: vec![event.event_id.clone()],
                    remediation,
                });
            }
        }

        let summary = format!(
            "{standard} compliance report: {total_events} event(s) analyzed, {} finding(s) ({} non-compliance, {} warning)",
            findings.len(),
            findings
                .iter()
                .filter(|f| f.finding_type == FindingType::NonCompliance)
                .count(),
            findings
                .iter()
                .filter(|f| f.finding_type == FindingType::Warning)
                .count(),
        );

        Ok(ComplianceReport {
            standard,
            report_id: Uuid::new_v4().to_string(),
            generated_at: Utc::now(),
            period_start: start_date,
            period_end: end_date,
            total_events,
            findings,
            summary,
        })
    }

    /// Query persisted audit events within `[start, end]` carrying `standard`'s
    /// compliance tag.
    ///
    /// Buffered events are flushed first so the report reflects the full trail.
    /// Only the File backend supports querying today; other backends return an
    /// explicit error rather than an empty result.
    async fn query_events(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
        standard: ComplianceStandard,
    ) -> Result<Vec<EnterpriseAuditEvent>> {
        // Ensure everything buffered has been persisted before querying.
        self.flush_buffer().await?;

        match self.config.storage.backend {
            AuditStorageBackend::File => {
                let path = self.config.storage.file_path.as_ref().ok_or_else(|| {
                    anyhow::anyhow!(
                        "Audit File storage backend selected but no file_path configured"
                    )
                })?;

                let contents = match tokio::fs::read_to_string(path).await {
                    Ok(contents) => contents,
                    // No file yet means no events have been recorded.
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
                    Err(e) => return Err(e.into()),
                };

                let mut events = Vec::new();
                for line in contents.lines() {
                    let line = line.trim();
                    if line.is_empty() {
                        continue;
                    }
                    let event: EnterpriseAuditEvent = serde_json::from_str(line)?;
                    if event.timestamp >= start
                        && event.timestamp <= end
                        && event.compliance_tags.contains(&standard)
                    {
                        events.push(event);
                    }
                }
                Ok(events)
            }
            other => Err(anyhow::anyhow!(
                "Compliance querying is not implemented for audit storage backend {:?}",
                other
            )),
        }
    }
}

/// Compliance report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceReport {
    /// Compliance standard
    pub standard: ComplianceStandard,
    /// Report ID
    pub report_id: String,
    /// Report generation timestamp
    pub generated_at: DateTime<Utc>,
    /// Report period start
    pub period_start: DateTime<Utc>,
    /// Report period end
    pub period_end: DateTime<Utc>,
    /// Total events analyzed
    pub total_events: u64,
    /// Compliance findings
    pub findings: Vec<ComplianceFinding>,
    /// Report summary
    pub summary: String,
}

/// Compliance finding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceFinding {
    /// Finding ID
    pub finding_id: String,
    /// Finding type
    pub finding_type: FindingType,
    /// Severity
    pub severity: AuditSeverity,
    /// Description
    pub description: String,
    /// Affected events
    pub affected_events: Vec<String>,
    /// Remediation steps
    pub remediation: Option<String>,
}

/// Compliance finding types
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum FindingType {
    NonCompliance,
    Warning,
    BestPractice,
}

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

    #[tokio::test]
    async fn test_audit_config_default() {
        let config = EnterpriseAuditConfig::default();
        assert!(config.enabled);
        assert_eq!(config.retention.retention_days, 365);
    }

    #[tokio::test]
    async fn test_audit_logger_creation() {
        let config = EnterpriseAuditConfig::default();
        let logger = EnterpriseAuditLogger::new(config);
        let metrics = logger.get_metrics().await;
        assert_eq!(metrics.events_total, 0);
    }

    #[tokio::test]
    async fn test_compliance_standard_display() {
        assert_eq!(ComplianceStandard::GDPR.to_string(), "GDPR");
        assert_eq!(ComplianceStandard::HIPAA.to_string(), "HIPAA");
        assert_eq!(ComplianceStandard::SOC2.to_string(), "SOC2");
    }

    fn temp_audit_config() -> EnterpriseAuditConfig {
        let mut config = EnterpriseAuditConfig::default();
        let path = std::env::temp_dir().join(format!("oxirs-audit-{}.jsonl", Uuid::new_v4()));
        config.storage.file_path = Some(path);
        config
    }

    fn sample_event(result: ActionResult) -> EnterpriseAuditEvent {
        EnterpriseAuditEvent {
            event_id: Uuid::new_v4().to_string(),
            timestamp: Utc::now(),
            event_type: AuditEventType::DataAccess,
            severity: AuditSeverity::Critical,
            user_id: Some("user-1".to_string()),
            source_ip: None,
            resource: "graph:secret".to_string(),
            action: "read".to_string(),
            result,
            details: HashMap::new(),
            compliance_tags: vec![ComplianceStandard::SOC2],
            session_id: None,
            request_id: None,
            correlation_id: None,
        }
    }

    #[tokio::test]
    async fn regression_audit_events_persisted_to_file() {
        let config = temp_audit_config();
        let path = config
            .storage
            .file_path
            .clone()
            .expect("file path configured");
        let logger = EnterpriseAuditLogger::new(config);

        logger
            .log_event(sample_event(ActionResult::Success))
            .await
            .unwrap();
        logger.flush_buffer().await.unwrap();

        // The audit trail must actually be written to disk (previously a no-op).
        let contents = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(contents.contains("graph:secret"));

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn regression_unimplemented_backend_fails_loud() {
        let mut config = temp_audit_config();
        config.storage.backend = AuditStorageBackend::S3;
        let logger = EnterpriseAuditLogger::new(config);

        logger
            .log_event(sample_event(ActionResult::Success))
            .await
            .unwrap();
        // Flushing to an unimplemented backend must error, not silently succeed.
        assert!(logger.flush_buffer().await.is_err());
        // Events must be retained in the buffer for a retry, not discarded.
        assert!(!logger.buffer.read().await.is_empty());
    }

    #[tokio::test]
    async fn regression_compliance_report_reflects_events() {
        let config = temp_audit_config();
        let path = config
            .storage
            .file_path
            .clone()
            .expect("file path configured");
        let logger = EnterpriseAuditLogger::new(config);

        logger
            .log_event(sample_event(ActionResult::Denied))
            .await
            .unwrap();
        logger
            .log_event(sample_event(ActionResult::Success))
            .await
            .unwrap();

        let start = Utc::now() - chrono::Duration::hours(1);
        let end = Utc::now() + chrono::Duration::hours(1);
        let report = logger
            .generate_compliance_report(ComplianceStandard::SOC2, start, end)
            .await
            .unwrap();

        // Both SOC2-tagged events must be counted (previously always 0).
        assert_eq!(report.total_events, 2);
        // The denied event produces a non-compliance finding.
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].finding_type, FindingType::NonCompliance);

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn test_audit_severity_ordering() {
        assert!(AuditSeverity::Critical > AuditSeverity::Error);
        assert!(AuditSeverity::Error > AuditSeverity::Warning);
        assert!(AuditSeverity::Warning > AuditSeverity::Info);
        assert!(AuditSeverity::Info > AuditSeverity::Debug);
    }

    #[tokio::test]
    async fn test_action_result_display() {
        assert_eq!(ActionResult::Success.to_string(), "SUCCESS");
        assert_eq!(ActionResult::Failure.to_string(), "FAILURE");
        assert_eq!(ActionResult::Denied.to_string(), "DENIED");
    }
}