dbnexus 0.1.3

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
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
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
// Copyright (c) 2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! 审计日志模块
//!
//! 提供数据库操作审计功能,支持:
//! - CRUD 操作审计
//! - 用户身份追踪
//! - 敏感操作告警
//! - 审计日志持久化
//!
//! # Example
//!
//! ```rust,no_run
//! use dbnexus::audit::{AuditEvent, AuditLogger};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     let logger = AuditLogger::with_default_storage();
//!     let event = AuditEvent::create("users", "1", "admin");
//!
//!     tokio::runtime::Runtime::new()
//!         .unwrap()
//!         .block_on(async { logger.log(event).await })?;
//!
//!     Ok(())
//! }
//! ```

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sea_orm::ConnectionTrait;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use tokio::sync::Mutex;
use uuid::Uuid;

/// 审计操作类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AuditOperation {
    /// 创建操作
    Create,
    /// 读取操作
    Read,
    /// 更新操作
    Update,
    /// 删除操作
    Delete,
    /// 登录操作
    Login,
    /// 登出操作
    Logout,
    /// 权限变更
    PermissionChange,
    /// 配置变更
    ConfigChange,
    /// 其他操作
    Other(String),
}

impl fmt::Display for AuditOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuditOperation::Create => write!(f, "CREATE"),
            AuditOperation::Read => write!(f, "READ"),
            AuditOperation::Update => write!(f, "UPDATE"),
            AuditOperation::Delete => write!(f, "DELETE"),
            AuditOperation::Login => write!(f, "LOGIN"),
            AuditOperation::Logout => write!(f, "LOGOUT"),
            AuditOperation::PermissionChange => write!(f, "PERMISSION_CHANGE"),
            AuditOperation::ConfigChange => write!(f, "CONFIG_CHANGE"),
            AuditOperation::Other(s) => write!(f, "{}", s.to_uppercase()),
        }
    }
}

impl Default for AuditOperation {
    fn default() -> Self {
        AuditOperation::Other("UNKNOWN".to_string())
    }
}

/// 审计事件严重级别
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub enum AuditSeverity {
    /// 信息
    #[default]
    Info,
    ///    Low,
    ///    Medium,
    ///    High,
    /// 严重
    Critical,
}

impl fmt::Display for AuditSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuditSeverity::Info => write!(f, "INFO"),
            AuditSeverity::Low => write!(f, "LOW"),
            AuditSeverity::Medium => write!(f, "MEDIUM"),
            AuditSeverity::High => write!(f, "HIGH"),
            AuditSeverity::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// 审计结果
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub enum AuditResult {
    /// 成功
    #[default]
    Success,
    /// 失败
    Failure,
    /// 部分成功
    Partial,
    /// 未知
    Unknown,
}

impl fmt::Display for AuditResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuditResult::Success => write!(f, "SUCCESS"),
            AuditResult::Failure => write!(f, "FAILURE"),
            AuditResult::Partial => write!(f, "PARTIAL"),
            AuditResult::Unknown => write!(f, "UNKNOWN"),
        }
    }
}

/// 审计事件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEvent {
    /// 事件 ID
    pub id: String,
    /// 时间戳
    pub timestamp: DateTime<Utc>,
    /// 操作类型
    pub operation: AuditOperation,
    /// 实体类型(如 "users", "orders")
    pub entity_type: String,
    /// 实体 ID
    pub entity_id: String,
    /// 用户 ID
    pub user_id: String,
    /// 用户角色
    pub user_role: String,
    /// 客户端 IP
    pub client_ip: String,
    /// 事件严重级别
    pub severity: AuditSeverity,
    /// 操作结果
    pub result: AuditResult,
    /// 变更前的值(JSON)
    pub before_value: Option<String>,
    /// 变更后的值(JSON)
    pub after_value: Option<String>,
    /// 附加信息(JSON)
    pub extra: Option<String>,
    /// 请求 ID(用于追踪)
    pub request_id: String,
    /// 会话 ID
    pub session_id: String,
}

impl AuditEvent {
    /// 创建审计事件(推荐使用构建器模式)
    ///
    /// # 推荐方式
    /// 使用 `AuditEventBuilder` 进行链式构建:
    /// ```rust
    /// # use dbnexus::audit::{AuditEvent, AuditOperation, AuditSeverity};
    /// AuditEvent::builder()
    ///     .operation(AuditOperation::Create)
    ///     .entity_type("users")
    ///     .entity_id("1")
    ///     .user_id("admin")
    ///     .user_role("admin")
    ///     .client_ip("127.0.0.1")
    ///     .severity(AuditSeverity::High)
    ///     .build();
    /// ```
    ///
    /// # 简单方式
    /// 使用快捷方法:
    /// ```rust
    /// # use dbnexus::audit::{AuditEvent, AuditSeverity};
    /// AuditEvent::create("users", "1", "admin")
    ///     .with_severity(AuditSeverity::High);
    /// ```
    pub fn new(
        operation: AuditOperation,
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
        user_role: &str,
        client_ip: &str,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            timestamp: Utc::now(),
            operation,
            entity_type: entity_type.to_string(),
            entity_id: entity_id.to_string(),
            user_id: user_id.to_string(),
            user_role: user_role.to_string(),
            client_ip: client_ip.to_string(),
            severity: AuditSeverity::Info,
            result: AuditResult::Success,
            before_value: None,
            after_value: None,
            extra: None,
            request_id: Uuid::new_v4().to_string(),
            session_id: String::new(),
        }
    }

    /// 获取构建器
    pub fn builder() -> AuditEventBuilder {
        AuditEventBuilder::new()
    }

    /// 创建操作事件
    pub fn create(entity_type: &str, entity_id: &str, user_id: &str) -> Self {
        Self::new(AuditOperation::Create, entity_type, entity_id, user_id, "", "")
    }

    /// 读取操作事件
    pub fn read(entity_type: &str, entity_id: &str, user_id: &str) -> Self {
        Self::new(AuditOperation::Read, entity_type, entity_id, user_id, "", "")
    }

    /// 更新操作事件
    pub fn update(
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
        before: Option<String>,
        after: Option<String>,
    ) -> Self {
        let mut event = Self::new(AuditOperation::Update, entity_type, entity_id, user_id, "", "");
        event.before_value = before;
        event.after_value = after;
        event
    }

    /// 删除操作事件
    pub fn delete(entity_type: &str, entity_id: &str, user_id: &str) -> Self {
        Self::new(AuditOperation::Delete, entity_type, entity_id, user_id, "", "")
    }

    /// 设置用户信息
    pub fn with_user(mut self, role: &str, client_ip: &str) -> Self {
        self.user_role = role.to_string();
        self.client_ip = client_ip.to_string();
        self
    }

    /// 设置结果
    pub fn with_result(mut self, result: AuditResult) -> Self {
        self.result = result;
        self
    }

    /// 设置错误(Task 5.5: 修复 result 默认值)
    pub fn with_error(mut self, error: &str) -> Self {
        self.result = AuditResult::Failure;
        self.extra = Some(error.to_string());
        self
    }

    /// 设置严重级别
    pub fn with_severity(mut self, severity: AuditSeverity) -> Self {
        self.severity = severity;
        self
    }

    /// 设置附加信息
    pub fn with_extra(mut self, extra: &str) -> Self {
        self.extra = Some(extra.to_string());
        self
    }

    /// 设置变更前值
    pub fn with_before_value(mut self, value: &str) -> Self {
        self.before_value = Some(value.to_string());
        self
    }

    /// 设置变更后值
    pub fn with_after_value(mut self, value: &str) -> Self {
        self.after_value = Some(value.to_string());
        self
    }

    /// 设置请求 ID
    pub fn with_request_id(mut self, request_id: &str) -> Self {
        self.request_id = request_id.to_string();
        self
    }

    /// 设置会话 ID
    pub fn with_session_id(mut self, session_id: &str) -> Self {
        self.session_id = session_id.to_string();
        self
    }

    /// 转换为 JSON 字符串
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// 从 JSON 字符串解析
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// 对 JSON 值进行敏感数据脱敏
    ///
    /// 脱敏策略:
    /// - 识别 JSON 对象中的敏感字段
    /// - 将敏感字段的值替换为 "***REDACTED***"
    /// - 支持自定义敏感字段列表
    ///
    /// # Arguments
    ///
    /// * `value` - 原始 JSON 字符串
    /// * `sensitive_fields` - 敏感字段列表(默认包含常见敏感字段)
    ///
    /// # Returns
    ///
    /// 脱敏后的 JSON 字符串
    pub fn sanitize_value(value: &str, sensitive_fields: Option<Vec<String>>) -> String {
        // 默认敏感字段列表
        let default_sensitive = vec![
            "password".to_string(),
            "token".to_string(),
            "secret".to_string(),
            "key".to_string(),
            "credential".to_string(),
            "api_key".to_string(),
            "access_token".to_string(),
            "refresh_token".to_string(),
            "private_key".to_string(),
            "credit_card".to_string(),
            "ssn".to_string(),
            "social_security".to_string(),
        ];
        let fields = sensitive_fields.unwrap_or(default_sensitive);

        // 尝试解析 JSON
        if let Ok(serde_json::Value::Object(mut obj)) = serde_json::from_str::<serde_json::Value>(value) {
            for field in &fields {
                if let Some(_value) = obj.remove(field) {
                    // 记录原始值类型但不记录内容
                    tracing::debug!("Sensitive field '{}' redacted in audit log", field);
                }
            }
            // 脱敏后的值替换为占位符
            for field in &fields {
                obj.insert(field.clone(), serde_json::Value::String("***REDACTED***".to_string()));
            }
            return serde_json::to_string(&obj).unwrap_or_else(|_| "***SANITIZATION_ERROR***".to_string());
        }
        // 非 JSON 值,检查是否包含敏感关键字
        let lower = value.to_lowercase();
        for field in &fields {
            if lower.contains(&format!("\"{}\":", field)) || lower.contains(&format!("\"{}\" :", field)) {
                return "***REDACTED***".to_string();
            }
        }
        value.to_string()
    }

    /// 创建脱敏后的审计事件副本(用于日志记录)
    ///
    /// 返回一个副本,其中敏感数据已被脱敏
    pub fn sanitized(&self) -> Self {
        let sensitive_fields = vec![
            "password".to_string(),
            "token".to_string(),
            "secret".to_string(),
            "key".to_string(),
            "credential".to_string(),
        ];

        let mut sanitized = self.clone();
        if let Some(ref mut before) = sanitized.before_value {
            *before = Self::sanitize_value(before, Some(sensitive_fields.clone()));
        }
        if let Some(ref mut after) = sanitized.after_value {
            *after = Self::sanitize_value(after, Some(sensitive_fields.clone()));
        }
        if let Some(ref mut extra) = sanitized.extra {
            *extra = Self::sanitize_value(extra, Some(sensitive_fields.clone()));
        }
        sanitized
    }
}

/// 审计配置
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// 是否启用审计
    pub enabled: bool,
    /// 审计日志存储路径
    pub storage_path: Option<String>,
    /// 是否同步写入(影响性能但更安全)
    pub sync_write: bool,
    /// 日志文件最大大小(字节)
    pub max_file_size: u64,
    /// 保留日志文件数
    pub retention_count: u32,
    /// 敏感字段列表(记录时脱敏)
    pub sensitive_fields: Vec<String>,
    /// 需要高危告警的操作
    pub alert_operations: Vec<AuditOperation>,
    /// 高危操作的严重级别
    pub alert_severity: AuditSeverity,
    /// 最大重试次数(Task 5.8)
    pub max_retries: Option<u32>,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            storage_path: None,
            sync_write: false,
            max_file_size: 10 * 1024 * 1024, // 10MB
            retention_count: 7,
            sensitive_fields: vec![
                "password".to_string(),
                "token".to_string(),
                "secret".to_string(),
                "api_key".to_string(),
            ],
            alert_operations: vec![
                AuditOperation::Delete,
                AuditOperation::PermissionChange,
                AuditOperation::ConfigChange,
            ],
            alert_severity: AuditSeverity::High,
            max_retries: Some(3),
        }
    }
}

/// 审计存储后端特质
#[async_trait]
pub trait AuditStorage: Send + Sync {
    /// 存储审计事件
    async fn store(&self, event: &AuditEvent) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;

    /// 批量存储审计事件(Task 5.10)
    async fn store_batch(&self, events: &[AuditEvent]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // 默认实现:逐个存储
        for event in events {
            self.store(event).await?;
        }
        Ok(())
    }

    /// 查询审计事件
    async fn query(
        &self,
        filters: &AuditQueryFilters,
    ) -> Result<Vec<AuditEvent>, Box<dyn std::error::Error + Send + Sync>>;

    /// 清理旧日志
    async fn cleanup(&self, before: &DateTime<Utc>) -> Result<u64, Box<dyn std::error::Error + Send + Sync>>;
}

/// 审计查询过滤器
#[derive(Debug, Default)]
pub struct AuditQueryFilters {
    /// 用户 ID
    pub user_id: Option<String>,
    /// 实体类型
    pub entity_type: Option<String>,
    /// 操作类型
    pub operation: Option<AuditOperation>,
    /// 开始时间
    pub start_time: Option<DateTime<Utc>>,
    /// 结束时间
    pub end_time: Option<DateTime<Utc>>,
    /// 严重级别
    pub severity: Option<AuditSeverity>,
    /// 结果
    pub result: Option<AuditResult>,
}

/// 内存审计存储(默认实现)
#[derive(Debug)]
pub struct MemoryAuditStorage {
    events: Mutex<Vec<AuditEvent>>,
    max_events: usize,
    dropped_count: AtomicU64,
}

impl Default for MemoryAuditStorage {
    fn default() -> Self {
        Self::new(10000) // 默认最多存储 10000 条审计日志
    }
}

impl MemoryAuditStorage {
    /// 创建内存审计存储
    pub fn new(max_events: usize) -> Self {
        Self {
            events: Mutex::new(Vec::with_capacity(max_events)),
            max_events: if max_events == 0 { 10000 } else { max_events },
            dropped_count: AtomicU64::new(0),
        }
    }

    /// 获取已丢弃的事件数量
    pub fn dropped_count(&self) -> u64 {
        self.dropped_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// 获取当前事件数量
    pub async fn event_count(&self) -> usize {
        let events = self.events.lock().await;
        events.len()
    }
}

#[async_trait]
impl AuditStorage for MemoryAuditStorage {
    async fn store(&self, event: &AuditEvent) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let mut events = self.events.lock().await;

        // 如果超过最大容量,移除最旧的
        if events.len() >= self.max_events {
            events.remove(0);
            self.dropped_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }

        events.push(event.clone());

        Ok(())
    }

    async fn query(
        &self,
        filters: &AuditQueryFilters,
    ) -> Result<Vec<AuditEvent>, Box<dyn std::error::Error + Send + Sync>> {
        let events = self.events.lock().await;

        let mut result = events.clone();

        if let Some(user_id) = &filters.user_id {
            result.retain(|e| e.user_id == *user_id);
        }

        if let Some(entity_type) = &filters.entity_type {
            result.retain(|e| e.entity_type == *entity_type);
        }

        if let Some(operation) = &filters.operation {
            result.retain(|e| e.operation == *operation);
        }

        if let Some(start_time) = &filters.start_time {
            result.retain(|e| e.timestamp >= *start_time);
        }

        if let Some(end_time) = &filters.end_time {
            result.retain(|e| e.timestamp <= *end_time);
        }

        if let Some(severity) = &filters.severity {
            result.retain(|e| e.severity == *severity);
        }

        if let Some(result_status) = &filters.result {
            result.retain(|e| e.result == *result_status);
        }

        Ok(result)
    }

    async fn cleanup(&self, before: &DateTime<Utc>) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let mut events = self.events.lock().await;
        let before_count = events.len();
        events.retain(|e| e.timestamp > *before);
        let after_count = events.len();
        Ok((before_count - after_count) as u64)
    }
}

/// 文件审计存储(Task 5.1)
///
/// 将审计日志写入文件系统,支持:
/// - JSON 格式日志
/// - 按日期滚动文件
/// - 异步写入
#[derive(Debug)]
pub struct FileAuditStorage {
    /// 日志文件路径
    log_path: std::path::PathBuf,
    /// 文件句柄
    file: Mutex<tokio::fs::File>,
    /// 是否启用 JSON 格式
    json_format: bool,
}

impl FileAuditStorage {
    /// 创建文件审计存储
    ///
    /// # Errors
    ///
    /// 如果创建文件失败,返回错误
    pub async fn new(log_path: impl AsRef<std::path::Path>, json_format: bool) -> Result<Self, std::io::Error> {
        let log_path = log_path.as_ref().to_path_buf();

        // 确保父目录存在
        if let Some(parent) = log_path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }

        // 创建或追加文件
        let file = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .await?;

        Ok(Self {
            log_path,
            file: Mutex::new(file),
            json_format,
        })
    }

    /// 获取日志文件路径
    pub fn log_path(&self) -> &std::path::Path {
        &self.log_path
    }
}

#[async_trait]
impl AuditStorage for FileAuditStorage {
    async fn store(&self, event: &AuditEvent) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let log_line = if self.json_format {
            serde_json::to_string(event)?
        } else {
            format!(
                "[{}] {} - {} {} - {} - {}",
                event.timestamp.format("%Y-%m-%d %H:%M:%S%.3f"),
                event.user_id,
                event.operation,
                event.entity_type,
                event.entity_id,
                event.result
            )
        };

        let mut file = self.file.lock().await;
        tokio::io::AsyncWriteExt::write_all(&mut *file, (log_line + "\n").as_bytes()).await?;
        tokio::io::AsyncWriteExt::flush(&mut *file).await?;

        Ok(())
    }

    async fn query(
        &self,
        _filters: &AuditQueryFilters,
    ) -> Result<Vec<AuditEvent>, Box<dyn std::error::Error + Send + Sync>> {
        // 文件存储不支持查询,返回空列表
        // 可以通过读取文件并解析来实现,但这里简化处理
        Ok(Vec::new())
    }

    async fn cleanup(&self, _before: &DateTime<Utc>) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        // 文件存储不支持清理,返回 0
        // 可以通过重新写入文件来实现,但这里简化处理
        Ok(0)
    }
}

/// 数据库审计存储(Task 5.2)
///
/// 将审计日志写入数据库表,支持:
/// - 持久化存储
/// - 高效查询
/// - 批量写入
#[derive(Debug, Clone)]
pub struct DatabaseAuditStorage {
    /// 数据库连接
    pool: sea_orm::DatabaseConnection,
    /// 表名
    table_name: String,
}

impl DatabaseAuditStorage {
    /// 创建数据库审计存储
    ///
    /// # Errors
    ///
    /// 如果连接数据库失败,返回错误
    pub async fn new(pool: sea_orm::DatabaseConnection, table_name: Option<String>) -> Result<Self, sea_orm::DbErr> {
        let table_name = table_name.unwrap_or_else(|| "audit_logs".to_string());

        // 创建审计日志表(如果不存在)
        let create_table_sql = format!(
            r#"
            CREATE TABLE IF NOT EXISTS {} (
                id BIGSERIAL PRIMARY KEY,
                timestamp TIMESTAMPTZ NOT NULL,
                user_id VARCHAR(255) NOT NULL,
                operation VARCHAR(50) NOT NULL,
                entity_type VARCHAR(255),
                entity_id VARCHAR(255),
                severity VARCHAR(20) NOT NULL,
                result VARCHAR(20) NOT NULL,
                error_message TEXT,
                ip_address VARCHAR(45),
                user_agent TEXT,
                metadata JSONB,
                created_at TIMESTAMPTZ DEFAULT NOW()
            );
            
            CREATE INDEX IF NOT EXISTS idx_{}_timestamp ON {} (timestamp);
            CREATE INDEX IF NOT EXISTS idx_{}_user_id ON {} (user_id);
            CREATE INDEX IF NOT EXISTS idx_{}_entity_type ON {} (entity_type);
            "#,
            table_name, table_name, table_name, table_name, table_name, table_name, table_name
        );

        // 使用 sea_orm 的 Statement 执行 SQL
        pool.execute_raw(sea_orm::Statement::from_sql_and_values(
            sea_orm::DatabaseBackend::Postgres,
            &create_table_sql,
            vec![],
        ))
        .await?;

        Ok(Self { pool, table_name })
    }

    /// 获取表名
    pub fn table_name(&self) -> &str {
        &self.table_name
    }
}

#[async_trait]
impl AuditStorage for DatabaseAuditStorage {
    async fn store(&self, event: &AuditEvent) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let insert_sql = format!(
            r#"
            INSERT INTO {} (id, timestamp, user_id, operation, entity_type, entity_id, user_role, client_ip, severity, result, before_value, after_value, extra, request_id, session_id)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
            "#,
            self.table_name
        );

        // 使用 sea_orm 的 Statement 执行 SQL
        self.pool
            .execute_raw(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Postgres,
                &insert_sql,
                vec![
                    event.id.clone().into(),
                    event.timestamp.to_rfc3339().into(),
                    event.user_id.clone().into(),
                    event.operation.to_string().into(),
                    event.entity_type.clone().into(),
                    event.entity_id.clone().into(),
                    event.user_role.clone().into(),
                    event.client_ip.clone().into(),
                    event.severity.to_string().into(),
                    event.result.to_string().into(),
                    event.before_value.clone().unwrap_or_default().into(),
                    event.after_value.clone().unwrap_or_default().into(),
                    event.extra.clone().unwrap_or_default().into(),
                    event.request_id.clone().into(),
                    event.session_id.clone().into(),
                ],
            ))
            .await?;

        Ok(())
    }

    async fn query(
        &self,
        filters: &AuditQueryFilters,
    ) -> Result<Vec<AuditEvent>, Box<dyn std::error::Error + Send + Sync>> {
        let mut query = format!("SELECT * FROM {} WHERE 1=1", self.table_name);
        let mut conditions = Vec::new();
        let mut params = Vec::new();
        let mut param_index = 1;

        if let Some(user_id) = &filters.user_id {
            conditions.push(format!("user_id = ${}", param_index));
            params.push(user_id.clone());
            param_index += 1;
        }

        if let Some(entity_type) = &filters.entity_type {
            conditions.push(format!("entity_type = ${}", param_index));
            params.push(entity_type.clone());
            param_index += 1;
        }

        if let Some(operation) = &filters.operation {
            conditions.push(format!("operation = ${}", param_index));
            params.push(operation.to_string());
            param_index += 1;
        }

        if let Some(start_time) = &filters.start_time {
            conditions.push(format!("timestamp >= ${}", param_index));
            params.push(start_time.to_rfc3339());
            param_index += 1;
        }

        if let Some(end_time) = &filters.end_time {
            conditions.push(format!("timestamp <= ${}", param_index));
            params.push(end_time.to_rfc3339());
            param_index += 1;
        }

        if let Some(severity) = &filters.severity {
            conditions.push(format!("severity = ${}", param_index));
            params.push(severity.to_string());
            param_index += 1;
        }

        if let Some(result) = &filters.result {
            conditions.push(format!("result = ${}", param_index));
            params.push(result.to_string());
            param_index += 1;
        }

        if !conditions.is_empty() {
            query.push_str(" AND ");
            query.push_str(&conditions.join(" AND "));
        }

        query.push_str(" ORDER BY timestamp DESC LIMIT 1000");

        // 使用 sea_orm 的 Statement 执行查询
        let result = self
            .pool
            .query_all_raw(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Postgres,
                &query,
                params.into_iter().map(|s| s.into()).collect::<Vec<_>>(),
            ))
            .await?;

        let mut events = Vec::new();
        for row in result {
            let operation_str: String = row.try_get("", "operation")?;
            let operation = match operation_str.as_str() {
                "CREATE" => AuditOperation::Create,
                "READ" => AuditOperation::Read,
                "UPDATE" => AuditOperation::Update,
                "DELETE" => AuditOperation::Delete,
                "LOGIN" => AuditOperation::Login,
                "LOGOUT" => AuditOperation::Logout,
                "PERMISSION_CHANGE" => AuditOperation::PermissionChange,
                "CONFIG_CHANGE" => AuditOperation::ConfigChange,
                _ => AuditOperation::Other(operation_str),
            };

            let severity_str: String = row.try_get("", "severity")?;
            let severity = match severity_str.as_str() {
                "INFO" => AuditSeverity::Info,
                "LOW" => AuditSeverity::Low,
                "MEDIUM" => AuditSeverity::Medium,
                "HIGH" => AuditSeverity::High,
                "CRITICAL" => AuditSeverity::Critical,
                _ => AuditSeverity::Info,
            };

            let result_str: String = row.try_get("", "result")?;
            let result = match result_str.as_str() {
                "SUCCESS" => AuditResult::Success,
                "FAILURE" => AuditResult::Failure,
                _ => AuditResult::Success,
            };

            // 将字符串转换为 DateTime
            let timestamp_str: String = row.try_get("", "timestamp")?;
            let timestamp = DateTime::parse_from_rfc3339(&timestamp_str)?.with_timezone(&Utc);

            events.push(AuditEvent {
                id: row.try_get("", "id")?,
                timestamp,
                operation,
                entity_type: row.try_get("", "entity_type")?,
                entity_id: row.try_get("", "entity_id")?,
                user_id: row.try_get("", "user_id")?,
                user_role: row.try_get("", "user_role")?,
                client_ip: row.try_get("", "client_ip")?,
                severity,
                result,
                before_value: row.try_get("", "before_value")?,
                after_value: row.try_get("", "after_value")?,
                extra: row.try_get("", "extra")?,
                request_id: row.try_get("", "request_id")?,
                session_id: row.try_get("", "session_id")?,
            });
        }

        Ok(events)
    }

    async fn cleanup(&self, before: &DateTime<Utc>) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let delete_sql = format!("DELETE FROM {} WHERE timestamp < $1", self.table_name);

        let result = self
            .pool
            .execute_raw(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Postgres,
                &delete_sql,
                vec![before.to_rfc3339().into()],
            ))
            .await?;

        Ok(result.rows_affected())
    }

    async fn store_batch(&self, events: &[AuditEvent]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if events.is_empty() {
            return Ok(());
        }

        // 使用批量插入
        let mut values = Vec::new();
        for event in events {
            values.push(format!(
                "('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')",
                event.id.replace('\'', "''"),
                event.timestamp.to_rfc3339(),
                event.user_id.replace('\'', "''"),
                event.operation.to_string(),
                event.entity_type.replace('\'', "''"),
                event.entity_id.replace('\'', "''"),
                event.user_role.replace('\'', "''"),
                event.client_ip.replace('\'', "''"),
                event.severity.to_string(),
                event.result.to_string(),
                event
                    .before_value
                    .as_ref()
                    .map(|s| format!("'{}'", s.replace('\'', "''")))
                    .unwrap_or("NULL".to_string()),
                event
                    .after_value
                    .as_ref()
                    .map(|s| format!("'{}'", s.replace('\'', "''")))
                    .unwrap_or("NULL".to_string()),
                event
                    .extra
                    .as_ref()
                    .map(|s| format!("'{}'", s.replace('\'', "''")))
                    .unwrap_or("NULL".to_string()),
                event.request_id.replace('\'', "''"),
                event.session_id.replace('\'', "''")
            ));
        }

        let insert_sql = format!(
            "INSERT INTO {} (id, timestamp, user_id, operation, entity_type, entity_id, user_role, client_ip, severity, result, before_value, after_value, extra, request_id, session_id) VALUES {}",
            self.table_name,
            values.join(", ")
        );

        self.pool
            .execute_raw(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Postgres,
                &insert_sql,
                vec![],
            ))
            .await?;

        Ok(())
    }
}

/// 审计告警回调类型
type AuditAlertCallback = Arc<dyn Fn(&AuditEvent) + Send + Sync>;

/// 审计日志器
pub struct AuditLogger {
    /// 配置
    config: AuditConfig,
    /// 存储后端
    storage: Arc<dyn AuditStorage>,
    /// 告警回调
    alert_callback: Option<AuditAlertCallback>,
}

impl AuditLogger {
    /// 创建审计日志器
    pub fn new(config: AuditConfig, storage: Arc<dyn AuditStorage>) -> Self {
        Self {
            config,
            storage,
            alert_callback: None,
        }
    }

    /// 创建带默认配置的审计日志器
    pub fn with_default_storage() -> Self {
        Self::new(AuditConfig::default(), Arc::new(MemoryAuditStorage::new(10000)))
    }

    /// 设置告警回调
    pub fn set_alert_callback<F>(&mut self, callback: F)
    where
        F: Fn(&AuditEvent) + Send + Sync + 'static,
    {
        self.alert_callback = Some(Arc::new(callback));
    }

    /// 记录审计事件
    pub async fn log(&self, event: AuditEvent) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if !self.config.enabled {
            return Ok(());
        }

        // 脱敏处理
        let event = self.sanitize_event(event);

        // 存储事件(带重试机制 - Task 5.8)
        let max_retries = self.config.max_retries.unwrap_or(3);
        let mut last_error = None;

        for attempt in 0..=max_retries {
            match self.storage.store(&event).await {
                Ok(()) => break,
                Err(e) => {
                    last_error = Some(e);
                    if attempt < max_retries {
                        let delay = std::time::Duration::from_millis(100 * (2_u64.pow(attempt as u32)));
                        tokio::time::sleep(delay).await;
                        tracing::warn!(
                            "Audit log storage failed (attempt {}/{}), retrying after {:?}",
                            attempt + 1,
                            max_retries,
                            delay
                        );
                    }
                }
            }
        }

        if let Some(error) = last_error {
            tracing::error!("Failed to store audit event after {} retries: {}", max_retries, error);
            return Err(error);
        }

        // 检查是否需要告警
        if self.should_alert(&event) {
            self.trigger_alert(&event);
        }

        Ok(())
    }

    /// 记录创建操作
    pub async fn log_create(
        &self,
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
        value: Option<String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let event = AuditEvent::create(entity_type, entity_id, user_id);
        let event = match value {
            Some(ref v) => event.with_after_value(v),
            None => event,
        };
        self.log(event).await
    }

    /// 记录读取操作
    pub async fn log_read(
        &self,
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let event = AuditEvent::read(entity_type, entity_id, user_id);
        self.log(event).await
    }

    /// 记录更新操作
    pub async fn log_update(
        &self,
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
        before: Option<String>,
        after: Option<String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let event = AuditEvent::update(entity_type, entity_id, user_id, before, after);
        self.log(event).await
    }

    /// 记录删除操作
    pub async fn log_delete(
        &self,
        entity_type: &str,
        entity_id: &str,
        user_id: &str,
        before: Option<String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let event = AuditEvent::delete(entity_type, entity_id, user_id).with_severity(AuditSeverity::High);
        let event = match before {
            Some(ref v) => event.with_before_value(v),
            None => event,
        };
        self.log(event).await
    }

    /// 查询审计日志
    pub async fn query(
        &self,
        filters: &AuditQueryFilters,
    ) -> Result<Vec<AuditEvent>, Box<dyn std::error::Error + Send + Sync>> {
        self.storage.query(filters).await
    }

    /// 清理旧日志
    pub async fn cleanup(&self, days: i64) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let delta = chrono::Duration::try_days(days).ok_or("Invalid date calculation")?;
        let before = Utc::now().checked_sub_signed(delta).ok_or("Invalid date calculation")?;
        self.storage.cleanup(&before).await
    }

    /// 脱敏处理(Task 5.9: 优化性能)
    fn sanitize_event(&self, mut event: AuditEvent) -> AuditEvent {
        let sanitize_value = |value: Option<String>| -> Option<String> {
            if let Some(v) = value {
                // 如果没有敏感字段,直接返回
                if self.config.sensitive_fields.is_empty() {
                    return Some(v);
                }

                // 一次性构建所有替换模式(Task 5.9: 优化性能)
                let mut replacements = Vec::new();
                for field in &self.config.sensitive_fields {
                    let replacement = format!("***REDACTED_{}***", field.to_uppercase());

                    // 1. JSON 格式: "field":
                    replacements.push((format!(r#""{}":"#, field), format!(r#""{}":"#, &replacement)));

                    // 2. 非 JSON 格式: field:
                    replacements.push((format!(r#"{}:"#, field), format!(r#"{}:"#, &replacement)));

                    // 3. 嵌套字段 (如 user.password)
                    if field.contains('.') {
                        replacements.push((format!(r#""{}""#, field), format!(r#""{}""#, &replacement)));
                    }
                }

                // 应用所有替换(Task 5.9: 批量替换减少字符串分配)
                let mut result = v;
                for (pattern, replacement) in &replacements {
                    result = result.replace(pattern, replacement);
                }

                // 4. 通用 Base64 值检测和脱敏(不依赖 JSON 结构)
                for field in &self.config.sensitive_fields {
                    let replacement = format!("***REDACTED_{}***", field.to_uppercase());
                    result = Self::sanitize_generic_base64(&result, field, &replacement);

                    // 5. JSON 数组中的敏感字段脱敏
                    result = Self::sanitize_json_arrays(&result, field, &replacement);
                }

                Some(result)
            } else {
                None
            }
        };

        event.before_value = sanitize_value(event.before_value);
        event.after_value = sanitize_value(event.after_value);
        event.extra = sanitize_value(event.extra);

        event
    }

    /// 通用 Base64 值脱敏(不依赖 JSON 结构)
    fn sanitize_generic_base64(value: &str, field: &str, replacement: &str) -> String {
        let mut result = value.to_string();

        // 尝试解析为 JSON,如果失败仍然尝试脱敏
        if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(value) {
            // 如果是对象
            if let Some(obj) = json_val.as_object() {
                let mut modified = false;
                let mut new_obj = serde_json::Map::new();
                let underscore_str = String::from("_");
                let field_with_underscore = format!("{}{}", underscore_str, field);

                for (k, v) in obj {
                    // 检查字段名匹配
                    if k == field || k.contains(&field_with_underscore) {
                        let redacted_key = format!("{}{}redacted", k, underscore_str);
                        new_obj.insert(redacted_key, serde_json::Value::String(replacement.to_string()));
                        modified = true;
                    } else if v.is_string() {
                        let s = v.as_str().unwrap_or("");
                        // 检测并脱敏 Base64 编码
                        if Self::is_base64(s) {
                            new_obj.insert(k.clone(), serde_json::Value::String(replacement.to_string()));
                            modified = true;
                        } else {
                            new_obj.insert(k.clone(), v.clone());
                        }
                    } else {
                        new_obj.insert(k.clone(), v.clone());
                    }
                }

                if modified {
                    result = serde_json::to_string(&new_obj).unwrap_or(result);
                }
            }
            // 如果是数组,处理数组中的每个元素
            else if let Some(arr) = json_val.as_array() {
                let mut modified = false;
                let mut new_arr = Vec::new();

                for item in arr {
                    if let Some(obj) = item.as_object() {
                        let mut new_obj = serde_json::Map::new();
                        for (k, v) in obj {
                            let should_mask = k == field
                                || k.contains(field)
                                || (v.is_string() && Self::is_base64(v.as_str().unwrap_or("")));

                            if should_mask {
                                new_obj.insert(k.clone(), serde_json::Value::String(replacement.to_string()));
                                modified = true;
                            } else {
                                new_obj.insert(k.clone(), v.clone());
                            }
                        }
                        new_arr.push(serde_json::Value::Object(new_obj));
                    } else {
                        new_arr.push(item.clone());
                    }
                }

                if modified {
                    result = serde_json::to_string(&new_arr).unwrap_or(result);
                }
            }
        }

        result
    }

    /// 脱敏 JSON 数组中的敏感字段
    fn sanitize_json_arrays(value: &str, field: &str, replacement: &str) -> String {
        // 检测数组模式 [ {"field": "value"}, ... ]
        let array_pattern = format!(r#"{{"{}","#, field);
        if !value.contains(&array_pattern) {
            return value.to_string();
        }

        // 尝试解析并脱敏
        if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(value) {
            if let Some(arr) = json_val.as_array() {
                let mut modified = false;
                let mut new_arr = Vec::new();

                for item in arr {
                    if let Some(obj) = item.as_object() {
                        let mut new_obj = serde_json::Map::new();
                        for (k, v) in obj {
                            if k == field {
                                new_obj.insert(k.clone(), serde_json::Value::String(replacement.to_string()));
                                modified = true;
                            } else {
                                new_obj.insert(k.clone(), v.clone());
                            }
                        }
                        new_arr.push(serde_json::Value::Object(new_obj));
                    } else {
                        new_arr.push(item.clone());
                    }
                }

                if modified {
                    return serde_json::to_string(&new_arr).unwrap_or(value.to_string());
                }
            }
        }

        value.to_string()
    }

    /// 检测字符串是否为有效的 Base64 编码
    fn is_base64(s: &str) -> bool {
        if s.len() % 4 != 0 || s.is_empty() {
            return false;
        }
        let valid_chars: std::collections::HashSet<char> =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
                .chars()
                .collect();
        s.chars().all(|c| valid_chars.contains(&c) || c == '=')
    }

    /// 检查是否需要告警
    fn should_alert(&self, event: &AuditEvent) -> bool {
        if !self.config.enabled {
            return false;
        }

        self.config.alert_operations.contains(&event.operation)
    }

    /// 触发告警
    fn trigger_alert(&self, event: &AuditEvent) {
        if let Some(callback) = &self.alert_callback {
            callback(event);
        }

        let msg = format!(
            "[AUDIT ALERT] {} - {} {} on {} by user {}",
            event.severity, event.operation, event.entity_id, event.entity_type, event.user_id
        );
        tracing::warn!("{}", msg);
    }
}

/// 审计上下文(用于在请求中传递审计信息)
#[derive(Debug, Default, Clone)]
pub struct AuditContext {
    /// 用户 ID
    pub user_id: String,
    /// 用户角色
    pub user_role: String,
    /// 客户端 IP
    pub client_ip: String,
    /// 请求 ID
    pub request_id: String,
    /// 会话 ID
    pub session_id: String,
}

impl AuditContext {
    /// 创建审计上下文
    pub fn new(user_id: &str, role: &str, client_ip: &str) -> Self {
        Self {
            user_id: user_id.to_string(),
            user_role: role.to_string(),
            client_ip: client_ip.to_string(),
            request_id: Uuid::new_v4().to_string(),
            session_id: String::new(),
        }
    }

    /// 设置请求 ID
    pub fn with_request_id(mut self, request_id: &str) -> Self {
        self.request_id = request_id.to_string();
        self
    }

    /// 设置会话 ID
    pub fn with_session_id(mut self, session_id: &str) -> Self {
        self.session_id = session_id.to_string();
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    #[tokio::test]
    async fn test_audit_event_creation() {
        let event = AuditEvent::create("users", "1", "admin");
        assert_eq!(event.operation, AuditOperation::Create);
        assert_eq!(event.entity_type, "users");
        assert_eq!(event.entity_id, "1");
        assert_eq!(event.user_id, "admin");
    }

    #[tokio::test]
    async fn test_audit_event_update() {
        let before = r#"{"name": "old"}"#;
        let after = r#"{"name": "new"}"#;
        let event = AuditEvent::update("users", "1", "admin", Some(before.to_string()), Some(after.to_string()));

        assert_eq!(event.operation, AuditOperation::Update);
        assert_eq!(event.before_value, Some(before.to_string()));
        assert_eq!(event.after_value, Some(after.to_string()));
    }

    #[tokio::test]
    async fn test_audit_event_setters_and_default_storage() {
        let event = AuditEvent::create("users", "1", "admin")
            .with_user("role", "127.0.0.1")
            .with_result(AuditResult::Failure)
            .with_severity(AuditSeverity::High)
            .with_extra("x")
            .with_before_value("b")
            .with_after_value("a")
            .with_request_id("r")
            .with_session_id("s");

        assert_eq!(event.user_role, "role");
        assert_eq!(event.client_ip, "127.0.0.1");
        assert_eq!(event.result, AuditResult::Failure);
        assert_eq!(event.severity, AuditSeverity::High);
        assert_eq!(event.extra.as_deref(), Some("x"));
        assert_eq!(event.before_value.as_deref(), Some("b"));
        assert_eq!(event.after_value.as_deref(), Some("a"));
        assert_eq!(event.request_id, "r");
        assert_eq!(event.session_id, "s");

        let storage = MemoryAuditStorage::default();
        storage.store(&event).await.expect("Storage operation should succeed");
        assert_eq!(storage.event_count().await, 1);
    }

    #[test]
    fn test_audit_event_json_roundtrip() {
        let event = AuditEvent::create("users", "1", "admin")
            .with_user("role", "127.0.0.1")
            .with_result(AuditResult::Success)
            .with_severity(AuditSeverity::Medium)
            .with_extra("x")
            .with_before_value("b")
            .with_after_value("a")
            .with_request_id("r")
            .with_session_id("s");

        let json = event.to_json().unwrap();
        let parsed = AuditEvent::from_json(&json).unwrap();

        assert_eq!(parsed.operation, event.operation);
        assert_eq!(parsed.entity_type, event.entity_type);
        assert_eq!(parsed.entity_id, event.entity_id);
        assert_eq!(parsed.user_id, event.user_id);
        assert_eq!(parsed.user_role, event.user_role);
        assert_eq!(parsed.client_ip, event.client_ip);
        assert_eq!(parsed.result, event.result);
        assert_eq!(parsed.severity, event.severity);
        assert_eq!(parsed.extra, event.extra);
        assert_eq!(parsed.before_value, event.before_value);
        assert_eq!(parsed.after_value, event.after_value);
        assert_eq!(parsed.request_id, event.request_id);
        assert_eq!(parsed.session_id, event.session_id);
    }

    #[tokio::test]
    async fn test_audit_logger_helpers_and_alert_disabled() {
        let storage = Arc::new(MemoryAuditStorage::new(10));

        let logger = AuditLogger::new(
            AuditConfig {
                enabled: false,
                alert_operations: vec![AuditOperation::Delete],
                ..Default::default()
            },
            storage.clone(),
        );

        logger.log_create("t", "1", "u", Some("v".to_string())).await.unwrap();
        logger.log_read("t", "1", "u").await.unwrap();
        logger
            .log_update("t", "1", "u", Some("b".to_string()), Some("a".to_string()))
            .await
            .unwrap();
        logger.log_delete("t", "1", "u", None).await.unwrap();

        assert_eq!(storage.event_count().await, 0);
        assert!(!logger.should_alert(&AuditEvent::delete("t", "1", "u")));
    }

    #[tokio::test]
    async fn test_audit_log_create_none_branch_and_cleanup_success() {
        let storage = Arc::new(MemoryAuditStorage::new(10));
        let logger = AuditLogger::new(AuditConfig::default(), storage.clone());

        logger.log_create("t", "1", "u", None).await.unwrap();

        let mut old = AuditEvent::create("t", "2", "u");
        old.timestamp = Utc::now() - chrono::Duration::days(2);
        logger.log(old).await.unwrap();

        let removed = logger.cleanup(1).await.unwrap();
        assert_eq!(removed, 1);
        assert_eq!(storage.event_count().await, 1);
    }

    #[tokio::test]
    async fn test_audit_sanitize_base64_non_string_values() {
        let storage = Arc::new(MemoryAuditStorage::new(10));
        let logger = AuditLogger::new(AuditConfig::default(), storage);

        let event = AuditEvent::create("t", "1", "u").with_after_value(r#"{"count":1,"name":"x"}"#);
        logger.log(event).await.unwrap();

        let results = logger.query(&AuditQueryFilters::default()).await.unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].after_value.as_ref().unwrap().contains("count"));
    }

    #[tokio::test]
    async fn test_audit_logger() {
        let storage = Arc::new(MemoryAuditStorage::new(100));
        let config = AuditConfig::default();
        let logger = AuditLogger::new(config, storage);

        let event = AuditEvent::create("users", "1", "admin");
        logger.log(event).await.unwrap();

        let filters = AuditQueryFilters {
            entity_type: Some("users".to_string()),
            ..Default::default()
        };
        let results = logger.query(&filters).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].entity_type, "users");
    }

    #[tokio::test]
    async fn test_audit_sanitization() {
        let storage = Arc::new(MemoryAuditStorage::new(100));
        let config = AuditConfig::default();
        let logger = AuditLogger::new(config, storage);

        let event =
            AuditEvent::create("users", "1", "admin").with_after_value(r#"{"password": "secret123", "name": "test"}"#);

        logger.log(event).await.unwrap();

        let filters = AuditQueryFilters::default();
        let results = logger.query(&filters).await.unwrap();
        let after_value = results[0].after_value.as_ref().unwrap();

        // 密码应该被脱敏
        assert!(after_value.contains("***REDACTED_PASSWORD***"));
        assert!(after_value.contains("name"));
    }

    #[tokio::test]
    async fn test_audit_context() {
        let ctx = AuditContext::new("user123", "admin", "192.168.1.1");
        assert_eq!(ctx.user_id, "user123");
        assert_eq!(ctx.user_role, "admin");
        assert_eq!(ctx.client_ip, "192.168.1.1");
        assert!(!ctx.request_id.is_empty());
    }

    #[test]
    fn test_audit_enum_display_and_defaults() {
        assert_eq!(AuditOperation::Create.to_string(), "CREATE");
        assert_eq!(AuditOperation::Read.to_string(), "READ");
        assert_eq!(AuditOperation::Update.to_string(), "UPDATE");
        assert_eq!(AuditOperation::Delete.to_string(), "DELETE");
        assert_eq!(AuditOperation::Login.to_string(), "LOGIN");
        assert_eq!(AuditOperation::Logout.to_string(), "LOGOUT");
        assert_eq!(AuditOperation::PermissionChange.to_string(), "PERMISSION_CHANGE");
        assert_eq!(AuditOperation::ConfigChange.to_string(), "CONFIG_CHANGE");
        assert_eq!(AuditOperation::Other("custom_op".to_string()).to_string(), "CUSTOM_OP");
        assert_eq!(AuditOperation::default().to_string(), "UNKNOWN");

        assert_eq!(AuditSeverity::Info.to_string(), "INFO");
        assert_eq!(AuditSeverity::Low.to_string(), "LOW");
        assert_eq!(AuditSeverity::Medium.to_string(), "MEDIUM");
        assert_eq!(AuditSeverity::High.to_string(), "HIGH");
        assert_eq!(AuditSeverity::Critical.to_string(), "CRITICAL");

        assert_eq!(AuditResult::Success.to_string(), "SUCCESS");
        assert_eq!(AuditResult::Failure.to_string(), "FAILURE");
        assert_eq!(AuditResult::Partial.to_string(), "PARTIAL");
        assert_eq!(AuditResult::Unknown.to_string(), "UNKNOWN");
    }

    #[tokio::test]
    async fn test_memory_storage_overflow_and_dropped_count() {
        let storage = MemoryAuditStorage::new(1);
        assert_eq!(storage.dropped_count(), 0);

        let event1 = AuditEvent::create("users", "1", "admin");
        let event2 = AuditEvent::create("users", "2", "admin");

        storage.store(&event1).await.unwrap();
        storage.store(&event2).await.unwrap();

        assert_eq!(storage.event_count().await, 1);
        assert_eq!(storage.dropped_count(), 1);

        let results = storage.query(&AuditQueryFilters::default()).await.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].entity_id, "2");
    }

    #[tokio::test]
    async fn test_audit_query_filters_all_fields_and_cleanup() {
        let storage = Arc::new(MemoryAuditStorage::new(100));
        let logger = AuditLogger::new(AuditConfig::default(), storage.clone());

        let now = Utc::now();
        let mut e1 = AuditEvent::create("users", "1", "u1")
            .with_user("admin", "10.0.0.1")
            .with_severity(AuditSeverity::Low)
            .with_result(AuditResult::Success)
            .with_request_id("r1")
            .with_session_id("s1");
        e1.timestamp = now - chrono::Duration::minutes(10);

        let mut e2 = AuditEvent::delete("orders", "9", "u2")
            .with_user("system", "10.0.0.2")
            .with_severity(AuditSeverity::High)
            .with_result(AuditResult::Failure);
        e2.timestamp = now;

        logger.log(e1.clone()).await.unwrap();
        logger.log(e2.clone()).await.unwrap();

        let filters = AuditQueryFilters {
            user_id: Some("u2".to_string()),
            entity_type: Some("orders".to_string()),
            operation: Some(AuditOperation::Delete),
            start_time: Some(now - chrono::Duration::minutes(5)),
            end_time: Some(now + chrono::Duration::minutes(1)),
            severity: Some(AuditSeverity::High),
            result: Some(AuditResult::Failure),
        };

        let filtered = logger.query(&filters).await.unwrap();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].entity_id, "9");

        let removed = storage.cleanup(&(now - chrono::Duration::minutes(1))).await.unwrap();
        assert_eq!(removed, 1);
        assert_eq!(storage.event_count().await, 1);
    }

    #[tokio::test]
    async fn test_audit_logger_disabled_and_alert_callback() {
        let storage = Arc::new(MemoryAuditStorage::new(100));

        let disabled_logger = AuditLogger::new(
            AuditConfig {
                enabled: false,
                ..Default::default()
            },
            storage.clone(),
        );

        disabled_logger
            .log(AuditEvent::create("users", "1", "admin"))
            .await
            .unwrap();
        assert_eq!(storage.event_count().await, 0);

        let called = Arc::new(AtomicBool::new(false));
        let called_clone = called.clone();

        let mut logger = AuditLogger::with_default_storage();
        logger.set_alert_callback(move |_event| {
            called_clone.store(true, Ordering::SeqCst);
        });

        logger
            .log_delete("users", "2", "admin", Some(r#"{\"password\":\"x\"}"#.to_string()))
            .await
            .unwrap();
        assert!(called.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn test_audit_sanitization_base64_and_nested_field() {
        let storage = Arc::new(MemoryAuditStorage::new(100));
        let mut config = AuditConfig::default();
        config.sensitive_fields.push("user.password".to_string());
        let logger = AuditLogger::new(config, storage);

        let after_value = r#"{"password":"p","_password":"p2","data":"c2VjcmV0","user.password":"v"}"#;
        let event = AuditEvent::create("users", "1", "admin").with_after_value(after_value);
        logger.log(event).await.unwrap();

        let results = logger.query(&AuditQueryFilters::default()).await.unwrap();
        let stored = results[0].after_value.as_ref().unwrap();
        assert!(stored.contains("***REDACTED_PASSWORD***"));
        assert!(stored.contains("_password_redacted"));
        assert!(stored.contains(r#""data":"***REDACTED_PASSWORD***""#));
        assert!(stored.contains("***REDACTED_USER.PASSWORD***"));

        assert!(!AuditLogger::is_base64(""));
        assert!(!AuditLogger::is_base64("abc"));
        assert!(!AuditLogger::is_base64("!!!!"));
        assert!(AuditLogger::is_base64("c2VjcmV0"));
    }

    #[tokio::test]
    async fn test_audit_logger_cleanup_invalid_date_calculation() {
        let storage = Arc::new(MemoryAuditStorage::new(100));
        let logger = AuditLogger::new(AuditConfig::default(), storage);
        let result = logger.cleanup(i64::MAX).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_audit_context_setters() {
        let ctx = AuditContext::new("u", "r", "ip")
            .with_request_id("req")
            .with_session_id("sess");
        assert_eq!(ctx.request_id, "req");
        assert_eq!(ctx.session_id, "sess");
    }
}

/// 审计事件构建器
///
/// 提供链式 API 来构建 `AuditEvent`,避免大量参数:
/// ```rust
/// use dbnexus::audit::{AuditEvent, AuditOperation, AuditSeverity};
///
/// let event = AuditEvent::builder()
///     .operation(AuditOperation::Create)
///     .entity_type("users")
///     .entity_id("123")
///     .user_id("admin")
///     .user_role("administrator")
///     .client_ip("192.168.1.1")
///     .severity(AuditSeverity::High)
///     .result(dbnexus::audit::AuditResult::Success)
///     .before_value(r#"{"name":"old"}"#)
///     .after_value(r#"{"name":"new"}"#)
///     .extra(r#"{"reason":"update request"}"#)
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct AuditEventBuilder {
    operation: Option<AuditOperation>,
    entity_type: Option<String>,
    entity_id: Option<String>,
    user_id: Option<String>,
    user_role: Option<String>,
    client_ip: Option<String>,
    severity: AuditSeverity,
    result: AuditResult,
    before_value: Option<String>,
    after_value: Option<String>,
    extra: Option<String>,
    request_id: Option<String>,
    session_id: Option<String>,
}

impl AuditEventBuilder {
    /// 创建新构建器
    pub fn new() -> Self {
        Self {
            operation: None,
            entity_type: None,
            entity_id: None,
            user_id: None,
            user_role: None,
            client_ip: None,
            severity: AuditSeverity::Info,
            result: AuditResult::Success,
            before_value: None,
            after_value: None,
            extra: None,
            request_id: None,
            session_id: None,
        }
    }

    /// 设置操作类型
    pub fn operation(mut self, operation: AuditOperation) -> Self {
        self.operation = Some(operation);
        self
    }

    /// 设置实体类型
    pub fn entity_type(mut self, entity_type: &str) -> Self {
        self.entity_type = Some(entity_type.to_string());
        self
    }

    /// 设置实体 ID
    pub fn entity_id(mut self, entity_id: &str) -> Self {
        self.entity_id = Some(entity_id.to_string());
        self
    }

    /// 设置用户 ID
    pub fn user_id(mut self, user_id: &str) -> Self {
        self.user_id = Some(user_id.to_string());
        self
    }

    /// 设置用户角色
    pub fn user_role(mut self, user_role: &str) -> Self {
        self.user_role = Some(user_role.to_string());
        self
    }

    /// 设置客户端 IP
    pub fn client_ip(mut self, client_ip: &str) -> Self {
        self.client_ip = Some(client_ip.to_string());
        self
    }

    /// 设置严重级别
    pub fn severity(mut self, severity: AuditSeverity) -> Self {
        self.severity = severity;
        self
    }

    /// 设置操作结果
    pub fn result(mut self, result: AuditResult) -> Self {
        self.result = result;
        self
    }

    /// 设置变更前值(JSON)
    pub fn before_value(mut self, value: &str) -> Self {
        self.before_value = Some(value.to_string());
        self
    }

    /// 设置变更后值(JSON)
    pub fn after_value(mut self, value: &str) -> Self {
        self.after_value = Some(value.to_string());
        self
    }

    /// 设置附加信息(JSON)
    pub fn extra(mut self, value: &str) -> Self {
        self.extra = Some(value.to_string());
        self
    }

    /// 设置请求 ID
    pub fn request_id(mut self, request_id: &str) -> Self {
        self.request_id = Some(request_id.to_string());
        self
    }

    /// 设置会话 ID
    pub fn session_id(mut self, session_id: &str) -> Self {
        self.session_id = Some(session_id.to_string());
        self
    }

    /// 构建 AuditEvent
    ///
    /// # Panics
    /// 如果必需字段(operation, entity_type, entity_id)未设置会 panic
    pub fn build(self) -> AuditEvent {
        AuditEvent {
            id: Uuid::new_v4().to_string(),
            timestamp: Utc::now(),
            operation: self
                .operation
                .unwrap_or_else(|| panic!("AuditEventBuilder: operation is required")),
            entity_type: self
                .entity_type
                .unwrap_or_else(|| panic!("AuditEventBuilder: entity_type is required")),
            entity_id: self
                .entity_id
                .unwrap_or_else(|| panic!("AuditEventBuilder: entity_id is required")),
            user_id: self.user_id.unwrap_or_default(),
            user_role: self.user_role.unwrap_or_default(),
            client_ip: self.client_ip.unwrap_or_default(),
            severity: self.severity,
            result: self.result,
            before_value: self.before_value,
            after_value: self.after_value,
            extra: self.extra,
            request_id: self.request_id.unwrap_or_else(|| Uuid::new_v4().to_string()),
            session_id: self.session_id.unwrap_or_default(),
        }
    }
}