hammerwork 1.15.5

A high-performance, database-driven job queue for Rust with PostgreSQL and MySQL support, featuring job prioritization, cron scheduling, event streaming (Kafka/Kinesis/PubSub), webhooks, rate limiting, Prometheus metrics, and comprehensive monitoring
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
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
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
//! Advanced key management system for Hammerwork encryption.
//!
//! This module provides comprehensive key management capabilities including:
//! - Secure key generation and storage
//! - Key rotation and lifecycle management
//! - Master key encryption (Key Encryption Keys)
//! - External key management service integration (AWS KMS, Azure Key Vault, GCP KMS, HashiCorp Vault)
//! - Azure Key Vault integration for master key retrieval with automatic credential resolution
//! - Audit trails and key usage tracking
//!
//! # Security Considerations
//!
//! - Keys are never stored in plain text in the database
//! - Master keys are used to encrypt data encryption keys
//! - All key operations are logged for audit purposes
//! - Key access is controlled through proper authentication
//!
//! # Examples
//!
//! ## Basic Key Management
//!
//! ```rust,no_run
//! # #[cfg(feature = "encryption")]
//! # {
//! use hammerwork::encryption::{KeyManager, EncryptionAlgorithm, KeyManagerConfig};
//! use sqlx::{postgres::PgPool, Pool};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let database_url = "postgres://user:pass@localhost/hammerwork";
//! # let pool = sqlx::PgPool::connect(database_url).await?;
//! let config = KeyManagerConfig::new()
//!     .with_master_key_env("MASTER_KEY")
//!     .with_auto_rotation_enabled(true);
//!
//! let mut key_manager = KeyManager::new(config, pool).await?;
//!
//! // Generate a new encryption key
//! let key_id = key_manager.generate_key("payment-encryption", EncryptionAlgorithm::AES256GCM).await?;
//!
//! // Use the key for encryption operations
//! let key_material = key_manager.get_key(&key_id).await?;
//! # Ok(())
//! # }
//! # }
//! ```
//!
//! ## Key Rotation Workflow
//!
//! ```rust,no_run
//! # #[cfg(feature = "encryption")]
//! # {
//! use hammerwork::encryption::{KeyManager, EncryptionAlgorithm, KeyManagerConfig};
//! use sqlx::postgres::PgPool;
//! use chrono::Duration;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let database_url = "postgres://user:pass@localhost/hammerwork";
//! # let pool = sqlx::PgPool::connect(database_url).await?;
//! // Configure key manager with automatic rotation
//! let config = KeyManagerConfig::new()
//!     .with_master_key_env("MASTER_KEY")
//!     .with_auto_rotation_enabled(true)
//!     .with_rotation_interval(Duration::days(30))
//!     .with_max_key_versions(5);
//!
//! let mut key_manager = KeyManager::new(config, pool).await?;
//!
//! // Generate initial key
//! let key_id = key_manager.generate_key("user-data-key", EncryptionAlgorithm::AES256GCM).await?;
//! println!("Initial key generated: {}", key_id);
//!
//! // Check if key needs rotation
//! if key_manager.is_key_due_for_rotation(&key_id).await? {
//!     println!("Key is due for rotation");
//!     
//!     // Rotate the key
//!     let new_version = key_manager.rotate_key(&key_id).await?;
//!     println!("Key rotated to version: {}", new_version);
//!     
//!     // Update rotation schedule
//!     key_manager.update_key_rotation_schedule(&key_id, None).await?;
//! }
//!
//! // Perform automatic rotation for all keys
//! let rotated_keys = key_manager.perform_automatic_rotation().await?;
//! println!("Automatically rotated {} keys", rotated_keys.len());
//!
//! // Get key management statistics
//! let stats = key_manager.get_stats().await?;
//! println!("Total keys: {}, Rotations performed: {}",
//!          stats.total_keys, stats.rotations_performed);
//! # Ok(())
//! # }
//! # }
//! ```
//!
//! ## Azure Key Vault Master Key Integration
//!
//! ```rust,no_run
//! # #[cfg(all(feature = "encryption", feature = "azure-kv"))]
//! # {
//! use hammerwork::encryption::{KeyManager, KeyManagerConfig, KeySource};
//! use sqlx::postgres::PgPool;
//! use std::env;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let database_url = "postgres://user:pass@localhost/hammerwork";
//! # let pool = sqlx::PgPool::connect(database_url).await?;
//! // Set up Azure credentials via environment variables
//! env::set_var("AZURE_CLIENT_ID", "your-client-id");
//! env::set_var("AZURE_CLIENT_SECRET", "your-client-secret");
//! env::set_var("AZURE_TENANT_ID", "your-tenant-id");
//!
//! // Configure key manager with Azure Key Vault for master key
//! let config = KeyManagerConfig::new()
//!     .with_master_key_source(KeySource::External(
//!         "azure://my-vault.vault.azure.net/keys/master-key".to_string()
//!     ))
//!     .with_auto_rotation_enabled(true);
//!
//! let mut key_manager = KeyManager::new(config, pool).await?;
//!
//! // Master key is automatically loaded from Azure Key Vault
//! // If Azure Key Vault is unavailable, falls back to deterministic generation
//! let key_id = key_manager.generate_key("payment-key",
//!     hammerwork::encryption::EncryptionAlgorithm::AES256GCM).await?;
//!
//! println!("Generated key with Azure Key Vault master key: {}", key_id);
//! # Ok(())
//! # }
//! # }
//! ```

use super::{EncryptionAlgorithm, EncryptionError, KeySource};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use sqlx::{Database, Pool, Row};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tracing::{debug, error, info, warn};
use uuid::Uuid;

#[cfg(feature = "encryption")]
use {
    aes_gcm::{Aes256Gcm, Key as AesKey, KeyInit, Nonce, aead::Aead},
    base64::Engine,
    rand::{RngCore, rngs::OsRng},
};

/// Configuration for the key management system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyManagerConfig {
    /// Source for the master key used to encrypt data encryption keys
    pub master_key_source: KeySource,

    /// Whether to enable automatic key rotation
    pub auto_rotation_enabled: bool,

    /// Default rotation interval for automatically rotated keys
    pub default_rotation_interval: Duration,

    /// Maximum number of key versions to keep for each key ID
    pub max_key_versions: u32,

    /// Whether to enable key usage auditing
    pub audit_enabled: bool,

    /// External key management service configuration
    pub external_kms_config: Option<ExternalKmsConfig>,

    /// Key derivation configuration for password-based keys
    pub key_derivation_config: KeyDerivationConfig,
}

/// Configuration for external Key Management Service integration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalKmsConfig {
    /// KMS service type (AWS, GCP, Azure, HashiCorp Vault, etc.)
    pub service_type: String,

    /// Service endpoint URL
    pub endpoint: String,

    /// Authentication configuration
    pub auth_config: HashMap<String, String>,

    /// Region or availability zone
    pub region: Option<String>,

    /// Key namespace or project ID
    pub namespace: Option<String>,
}

/// Configuration for key derivation from passwords or passphrases
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyDerivationConfig {
    /// Argon2 memory cost parameter (in KB)
    pub memory_cost: u32,

    /// Argon2 time cost parameter (iterations)
    pub time_cost: u32,

    /// Argon2 parallelism parameter (threads)
    pub parallelism: u32,

    /// Salt length for key derivation
    pub salt_length: usize,
}

/// Represents an encryption key with its metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionKey {
    /// Unique identifier for the key
    pub id: Uuid,

    /// Human-readable key identifier
    pub key_id: String,

    /// Key version number
    pub version: u32,

    /// Encryption algorithm this key is used for
    pub algorithm: EncryptionAlgorithm,

    /// Encrypted key material (never stored in plain text)
    pub encrypted_key_material: Vec<u8>,

    /// Salt used for key derivation (if applicable)
    pub derivation_salt: Option<Vec<u8>>,

    /// How this key was created
    pub source: KeySource,

    /// Purpose of this key
    pub purpose: KeyPurpose,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Who or what created this key
    pub created_by: Option<String>,

    /// When this key expires (if applicable)
    pub expires_at: Option<DateTime<Utc>>,

    /// When this key was rotated (if applicable)
    pub rotated_at: Option<DateTime<Utc>>,

    /// When this key was retired
    pub retired_at: Option<DateTime<Utc>>,

    /// Current status of the key
    pub status: KeyStatus,

    /// How often to rotate this key automatically
    pub rotation_interval: Option<Duration>,

    /// When the next rotation is scheduled
    pub next_rotation_at: Option<DateTime<Utc>>,

    /// Key strength in bits
    pub key_strength: u32,

    /// ID of the master key used to encrypt this key
    pub master_key_id: Option<Uuid>,

    /// Audit trail information
    pub last_used_at: Option<DateTime<Utc>>,
    pub usage_count: u64,
}

/// Purpose of an encryption key
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum KeyPurpose {
    /// Data encryption key for encrypting job payloads
    Encryption,
    /// Message Authentication Code key
    MAC,
    /// Key Encryption Key (master key for encrypting other keys)
    KEK,
}

/// Current status of an encryption key
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum KeyStatus {
    /// Key is active and can be used for encryption and decryption
    Active,
    /// Key has been retired but can still be used for decryption
    Retired,
    /// Key has been revoked and should not be used
    Revoked,
    /// Key has expired based on its expiration time
    Expired,
}

/// Key usage audit record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyAuditRecord {
    /// Unique audit record ID
    pub id: Uuid,

    /// Key that was accessed
    pub key_id: String,

    /// Type of operation performed
    pub operation: KeyOperation,

    /// When the operation occurred
    pub timestamp: DateTime<Utc>,

    /// Who or what performed the operation
    pub actor: Option<String>,

    /// Additional context about the operation
    pub context: HashMap<String, String>,

    /// Whether the operation was successful
    pub success: bool,

    /// Error message if the operation failed
    pub error_message: Option<String>,
}

/// Types of key operations that can be audited
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum KeyOperation {
    /// Key was created
    Create,
    /// Key material was retrieved for use
    Access,
    /// Key was rotated to a new version
    Rotate,
    /// Key was retired
    Retire,
    /// Key was revoked
    Revoke,
    /// Key was deleted
    Delete,
    /// Key metadata was updated
    Update,
}

/// Statistics about key management operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyManagerStats {
    /// Total number of keys managed
    pub total_keys: u64,

    /// Number of active keys
    pub active_keys: u64,

    /// Number of retired keys
    pub retired_keys: u64,

    /// Number of revoked keys
    pub revoked_keys: u64,

    /// Number of expired keys
    pub expired_keys: u64,

    /// Total key access operations
    pub total_access_operations: u64,

    /// Number of key rotations performed
    pub rotations_performed: u64,

    /// Average key age in days
    pub average_key_age_days: f64,

    /// Keys approaching expiration (within 7 days)
    pub keys_expiring_soon: u64,

    /// Keys due for rotation
    pub keys_due_for_rotation: u64,
}

/// Main key management system
type KeyCacheEntry = (Vec<u8>, DateTime<Utc>); // (decrypted_material, cached_at)
type KeyCache = Arc<Mutex<HashMap<String, KeyCacheEntry>>>;

pub struct KeyManager<DB: Database> {
    config: KeyManagerConfig,
    #[allow(dead_code)]
    pool: Pool<DB>,
    master_key: Arc<Mutex<Option<Vec<u8>>>>,
    master_key_id: Arc<Mutex<Option<Uuid>>>,
    key_cache: KeyCache,
    stats: Arc<Mutex<KeyManagerStats>>,
}

impl<DB: Database> Clone for KeyManager<DB> {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            pool: self.pool.clone(),
            master_key: self.master_key.clone(),
            master_key_id: self.master_key_id.clone(),
            key_cache: self.key_cache.clone(),
            stats: self.stats.clone(),
        }
    }
}

impl Default for KeyManagerConfig {
    fn default() -> Self {
        Self {
            master_key_source: KeySource::Environment("HAMMERWORK_MASTER_KEY".to_string()),
            auto_rotation_enabled: false,
            default_rotation_interval: Duration::days(90), // 3 months
            max_key_versions: 10,
            audit_enabled: true,
            external_kms_config: None,
            key_derivation_config: KeyDerivationConfig::default(),
        }
    }
}

impl Default for KeyDerivationConfig {
    fn default() -> Self {
        Self {
            memory_cost: 65536, // 64 MB
            time_cost: 3,       // 3 iterations
            parallelism: 4,     // 4 threads
            salt_length: 32,    // 32 bytes
        }
    }
}

impl KeyManagerConfig {
    /// Create a new key manager configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManagerConfig, KeySource};
    /// use chrono::Duration;
    ///
    /// // Create default configuration
    /// let config = KeyManagerConfig::new();
    /// assert_eq!(config.auto_rotation_enabled, false);
    /// assert_eq!(config.max_key_versions, 10);
    /// assert_eq!(config.audit_enabled, true);
    /// # }
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the master key source
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManagerConfig, KeySource};
    ///
    /// let config = KeyManagerConfig::new()
    ///     .with_master_key_source(KeySource::Static("my-master-key".to_string()));
    /// # }
    /// ```
    pub fn with_master_key_source(mut self, source: KeySource) -> Self {
        self.master_key_source = source;
        self
    }

    /// Set the master key from an environment variable
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManagerConfig, KeySource};
    ///
    /// let config = KeyManagerConfig::new()
    ///     .with_master_key_env("MASTER_KEY");
    ///
    /// // This is equivalent to:
    /// let config2 = KeyManagerConfig::new()
    ///     .with_master_key_source(KeySource::Environment("MASTER_KEY".to_string()));
    /// # }
    /// ```
    pub fn with_master_key_env(mut self, env_var: &str) -> Self {
        self.master_key_source = KeySource::Environment(env_var.to_string());
        self
    }

    /// Enable or disable automatic key rotation
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::KeyManagerConfig;
    /// use chrono::Duration;
    ///
    /// let config = KeyManagerConfig::new()
    ///     .with_auto_rotation_enabled(true)
    ///     .with_rotation_interval(Duration::days(30));
    ///
    /// assert_eq!(config.auto_rotation_enabled, true);
    /// # }
    /// ```
    pub fn with_auto_rotation_enabled(mut self, enabled: bool) -> Self {
        self.auto_rotation_enabled = enabled;
        self
    }

    /// Set the default rotation interval
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::KeyManagerConfig;
    /// use chrono::Duration;
    ///
    /// // Rotate keys every 30 days
    /// let config = KeyManagerConfig::new()
    ///     .with_rotation_interval(Duration::days(30));
    ///
    /// // Or rotate keys every 24 hours for high-security scenarios
    /// let config2 = KeyManagerConfig::new()
    ///     .with_rotation_interval(Duration::hours(24));
    /// # }
    /// ```
    pub fn with_rotation_interval(mut self, interval: Duration) -> Self {
        self.default_rotation_interval = interval;
        self
    }

    /// Set the maximum number of key versions to retain
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::KeyManagerConfig;
    ///
    /// // Keep only 5 versions of each key
    /// let config = KeyManagerConfig::new()
    ///     .with_max_key_versions(5);
    ///
    /// // Keep up to 50 versions for compliance requirements
    /// let config2 = KeyManagerConfig::new()
    ///     .with_max_key_versions(50);
    /// # }
    /// ```
    pub fn with_max_key_versions(mut self, max_versions: u32) -> Self {
        self.max_key_versions = max_versions;
        self
    }

    /// Enable or disable key usage auditing
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::KeyManagerConfig;
    ///
    /// // Disable auditing for performance-critical applications
    /// let config = KeyManagerConfig::new()
    ///     .with_audit_enabled(false);
    ///
    /// // Enable auditing for compliance (default)
    /// let config2 = KeyManagerConfig::new()
    ///     .with_audit_enabled(true);
    /// # }
    /// ```
    pub fn with_audit_enabled(mut self, enabled: bool) -> Self {
        self.audit_enabled = enabled;
        self
    }

    /// Configure external KMS integration
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManagerConfig, ExternalKmsConfig};
    /// use std::collections::HashMap;
    ///
    /// let mut auth_config = HashMap::new();
    /// auth_config.insert("access_key".to_string(), "AKIA...".to_string());
    /// auth_config.insert("secret_key".to_string(), "secret...".to_string());
    ///
    /// let kms_config = ExternalKmsConfig {
    ///     service_type: "aws-kms".to_string(),
    ///     endpoint: "https://kms.us-east-1.amazonaws.com".to_string(),
    ///     auth_config,
    ///     region: Some("us-east-1".to_string()),
    ///     namespace: None,
    /// };
    ///
    /// let config = KeyManagerConfig::new()
    ///     .with_external_kms(kms_config);
    /// # }
    /// ```
    pub fn with_external_kms(mut self, config: ExternalKmsConfig) -> Self {
        self.external_kms_config = Some(config);
        self
    }
}

impl<DB: Database> KeyManager<DB>
where
    for<'c> &'c mut DB::Connection: sqlx::Executor<'c, Database = DB>,
    for<'q> <DB as sqlx::Database>::Arguments<'q>: sqlx::IntoArguments<'q, DB>,
    for<'r> String: sqlx::Decode<'r, DB> + sqlx::Type<DB>,
    for<'r> &'r str: sqlx::ColumnIndex<DB::Row>,
{
    /// Create a new key manager instance
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration for the key manager
    /// * `pool` - Database connection pool
    ///
    /// # Returns
    ///
    /// A new `KeyManager` instance with initialized master key and statistics
    ///
    /// # Examples
    ///
    /// ## Basic PostgreSQL setup
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, KeyManagerConfig, KeySource};
    /// use sqlx::PgPool;
    /// use std::env;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Set up environment variable for master key
    /// env::set_var("MASTER_KEY", "my-super-secret-master-key-32-chars");
    ///
    /// let pool = PgPool::connect("postgresql://user:pass@localhost/hammerwork").await?;
    /// let config = KeyManagerConfig::new()
    ///     .with_master_key_env("MASTER_KEY")
    ///     .with_auto_rotation_enabled(true);
    ///
    /// let key_manager = KeyManager::new(config, pool).await?;
    /// println!("Key manager initialized successfully");
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    ///
    /// ## MySQL setup with static master key
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, KeyManagerConfig, KeySource};
    /// use sqlx::MySqlPool;
    /// use chrono::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let pool = MySqlPool::connect("mysql://user:pass@localhost/hammerwork").await?;
    /// let config = KeyManagerConfig::new()
    ///     .with_master_key_source(KeySource::Static("my-32-char-master-key-here!!".to_string()))
    ///     .with_auto_rotation_enabled(true)
    ///     .with_default_rotation_interval(Duration::days(30));
    ///
    /// let key_manager = KeyManager::new(config, pool).await?;
    /// println!("MySQL key manager initialized with 30-day rotation");
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn new(config: KeyManagerConfig, pool: Pool<DB>) -> Result<Self, EncryptionError> {
        let manager = Self {
            config,
            pool,
            master_key: Arc::new(Mutex::new(None)),
            master_key_id: Arc::new(Mutex::new(None)),
            key_cache: Arc::new(Mutex::new(HashMap::new())),
            stats: Arc::new(Mutex::new(KeyManagerStats::default())),
        };

        // Initialize the master key
        manager.load_master_key().await?;

        // Load initial statistics
        manager.refresh_stats().await?;

        Ok(manager)
    }

    /// Generate a new encryption key
    ///
    /// # Arguments
    ///
    /// * `key_id` - Human-readable identifier for the key
    /// * `algorithm` - Encryption algorithm to use for this key
    ///
    /// # Returns
    ///
    /// The generated key ID string that can be used to retrieve the key later
    ///
    /// # Examples
    ///
    /// ## Generate different types of encryption keys
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionAlgorithm};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Generate a key for payment processing
    /// let payment_key = key_manager.generate_key(
    ///     "payment-encryption-v1",
    ///     EncryptionAlgorithm::AES256GCM
    /// ).await?;
    /// println!("Payment key generated: {}", payment_key);
    ///
    /// // Generate a key for user data
    /// let user_data_key = key_manager.generate_key(
    ///     "user-data-encryption",
    ///     EncryptionAlgorithm::ChaCha20Poly1305
    /// ).await?;
    /// println!("User data key generated: {}", user_data_key);
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    ///
    /// ## Generate with key ID pattern
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionAlgorithm};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Use consistent naming pattern for keys
    /// let keys = vec![
    ///     ("prod-api-encryption-2024", EncryptionAlgorithm::AES256GCM),
    ///     ("prod-db-encryption-2024", EncryptionAlgorithm::AES256GCM),
    ///     ("prod-file-encryption-2024", EncryptionAlgorithm::ChaCha20Poly1305),
    /// ];
    ///
    /// for (key_id, algorithm) in keys {
    ///     let generated_key = key_manager.generate_key(key_id, algorithm).await?;
    ///     println!("Generated key: {} -> {}", key_id, generated_key);
    /// }
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn generate_key(
        &mut self,
        key_id: &str,
        algorithm: EncryptionAlgorithm,
    ) -> Result<String, EncryptionError> {
        self.generate_key_with_options(
            key_id,
            algorithm,
            KeyPurpose::Encryption,
            None, // No expiration
            None, // No rotation interval
        )
        .await
    }

    /// Generate a new encryption key with detailed options
    pub async fn generate_key_with_options(
        &mut self,
        key_id: &str,
        algorithm: EncryptionAlgorithm,
        purpose: KeyPurpose,
        expires_at: Option<DateTime<Utc>>,
        rotation_interval: Option<Duration>,
    ) -> Result<String, EncryptionError> {
        #[cfg(not(feature = "encryption"))]
        {
            return Err(EncryptionError::InvalidConfiguration(
                "Encryption feature is not enabled".to_string(),
            ));
        }

        #[cfg(feature = "encryption")]
        {
            info!("Generating new encryption key: {}", key_id);

            // Generate random key material
            let key_length = match algorithm {
                EncryptionAlgorithm::AES256GCM => 32,
                EncryptionAlgorithm::ChaCha20Poly1305 => 32,
            };
            let key_strength = key_length * 8;
            let mut key_material = vec![0u8; key_length];
            OsRng.fill_bytes(&mut key_material);

            // Encrypt the key material with the master key
            let encrypted_key_material = self.encrypt_key_material(&key_material).await?;

            // Create the key record
            let key_record = EncryptionKey {
                id: Uuid::new_v4(),
                key_id: key_id.to_string(),
                version: 1,
                algorithm,
                encrypted_key_material,
                derivation_salt: None,
                source: KeySource::Generated("database".to_string()),
                purpose,
                created_at: Utc::now(),
                created_by: Some("hammerwork".to_string()),
                expires_at,
                rotated_at: None,
                retired_at: None,
                status: KeyStatus::Active,
                rotation_interval,
                next_rotation_at: rotation_interval.map(|interval| Utc::now() + interval),
                key_strength: key_strength as u32,
                master_key_id: self.get_master_key_id().await,
                last_used_at: None,
                usage_count: 0,
            };

            // Store the key in the database
            self.store_key(&key_record).await?;

            // Add to cache
            self.cache_key(key_id, key_material).await;

            // Record audit event
            if self.config.audit_enabled {
                self.record_audit_event(key_id, KeyOperation::Create, true, None)
                    .await?;
            }

            // Update statistics
            self.increment_key_count().await;

            info!("Successfully generated encryption key: {}", key_id);
            Ok(key_id.to_string())
        }
    }

    /// Retrieve key material for encryption/decryption operations
    ///
    /// # Arguments
    ///
    /// * `key_id` - The identifier of the key to retrieve
    ///
    /// # Returns
    ///
    /// The decrypted key material ready for use in encryption/decryption operations
    ///
    /// # Examples
    ///
    /// ## Retrieve a key for encryption
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionAlgorithm};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// // First generate a key
    /// let key_id = key_manager.generate_key(
    ///     "api-encryption-key",
    ///     EncryptionAlgorithm::AES256GCM
    /// ).await?;
    ///
    /// // Retrieve the key material for use
    /// let key_material = key_manager.get_key(&key_id).await?;
    /// println!("Retrieved key material: {} bytes", key_material.len());
    ///
    /// // Key material can now be used for encryption operations
    /// assert_eq!(key_material.len(), 32); // AES-256 key size
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    ///
    /// ## Handle key retrieval errors
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionError};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Try to retrieve a non-existent key
    /// match key_manager.get_key("non-existent-key").await {
    ///     Ok(key_material) => {
    ///         println!("Key retrieved successfully: {} bytes", key_material.len());
    ///     }
    ///     Err(EncryptionError::KeyNotFound(key_id)) => {
    ///         println!("Key '{}' not found", key_id);
    ///     }
    ///     Err(EncryptionError::KeyManagement(msg)) => {
    ///         println!("Key management error: {}", msg);
    ///     }
    ///     Err(e) => {
    ///         println!("Other error: {}", e);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn get_key(&mut self, key_id: &str) -> Result<Vec<u8>, EncryptionError> {
        // Check cache first
        if let Some(cached_key) = self.get_cached_key(key_id).await {
            self.record_key_usage(key_id).await?;
            return Ok(cached_key);
        }

        // Load from database
        let key_record = self.load_key(key_id).await?;

        // Verify key is usable
        if key_record.status == KeyStatus::Revoked {
            return Err(EncryptionError::KeyManagement(format!(
                "Key {} has been revoked",
                key_id
            )));
        }

        if let Some(expires_at) = key_record.expires_at {
            if Utc::now() > expires_at {
                return Err(EncryptionError::KeyManagement(format!(
                    "Key {} has expired",
                    key_id
                )));
            }
        }

        // Decrypt the key material
        let key_material = self
            .decrypt_key_material(&key_record.encrypted_key_material)
            .await?;

        // Cache the decrypted key
        self.cache_key(key_id, key_material.clone()).await;

        // Record usage
        self.record_key_usage(key_id).await?;

        // Record audit event
        if self.config.audit_enabled {
            self.record_audit_event(key_id, KeyOperation::Access, true, None)
                .await?;
        }

        Ok(key_material)
    }

    /// Rotate a key to a new version
    ///
    /// Creates a new version of the specified key while keeping the old version
    /// available for decryption of previously encrypted data.
    ///
    /// # Arguments
    ///
    /// * `key_id` - The identifier of the key to rotate
    ///
    /// # Returns
    ///
    /// The new version number of the rotated key
    ///
    /// # Examples
    ///
    /// ## Basic key rotation
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionAlgorithm};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Generate initial key
    /// let key_id = key_manager.generate_key(
    ///     "payment-processing-key",
    ///     EncryptionAlgorithm::AES256GCM
    /// ).await?;
    ///
    /// // Rotate the key to a new version
    /// let new_version = key_manager.rotate_key(&key_id).await?;
    /// println!("Key rotated to version: {}", new_version);
    ///
    /// // Old version is still available for decryption
    /// // New version will be used for new encryption operations
    /// assert_eq!(new_version, 2); // Should be version 2 after first rotation
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    ///
    /// ## Key rotation with usage tracking
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{KeyManager, EncryptionAlgorithm};
    ///
    /// # async fn example(mut key_manager: KeyManager<sqlx::Postgres>) -> Result<(), Box<dyn std::error::Error>> {
    /// let key_id = "user-data-encryption";
    ///
    /// // Generate initial key
    /// let initial_key = key_manager.generate_key(key_id, EncryptionAlgorithm::AES256GCM).await?;
    ///
    /// // Check if rotation is needed
    /// if key_manager.is_key_due_for_rotation(&initial_key).await? {
    ///     let new_version = key_manager.rotate_key(&initial_key).await?;
    ///     println!("Key {} rotated to version {}", key_id, new_version);
    ///     
    ///     // Update rotation schedule
    ///     key_manager.update_key_rotation_schedule(&initial_key, None).await?;
    /// }
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn rotate_key(&mut self, key_id: &str) -> Result<u32, EncryptionError> {
        #[cfg(not(feature = "encryption"))]
        {
            return Err(EncryptionError::InvalidConfiguration(
                "Encryption feature is not enabled".to_string(),
            ));
        }

        #[cfg(feature = "encryption")]
        {
            info!("Rotating encryption key: {}", key_id);

            // Load current key
            let current_key = self.load_key(key_id).await?;

            // Generate new key material
            let key_length = match current_key.algorithm {
                EncryptionAlgorithm::AES256GCM => 32,
                EncryptionAlgorithm::ChaCha20Poly1305 => 32,
            };
            let mut new_key_material = vec![0u8; key_length];
            OsRng.fill_bytes(&mut new_key_material);

            // Encrypt with master key
            let encrypted_key_material = self.encrypt_key_material(&new_key_material).await?;

            // Create new version
            let new_version = current_key.version + 1;
            let new_key_record = EncryptionKey {
                id: Uuid::new_v4(),
                key_id: key_id.to_string(),
                version: new_version,
                algorithm: current_key.algorithm,
                encrypted_key_material,
                derivation_salt: None,
                source: KeySource::Generated("rotation".to_string()),
                purpose: current_key.purpose,
                created_at: Utc::now(),
                created_by: Some("hammerwork-rotation".to_string()),
                expires_at: current_key.expires_at,
                rotated_at: Some(Utc::now()),
                retired_at: None,
                status: KeyStatus::Active,
                rotation_interval: current_key.rotation_interval,
                next_rotation_at: current_key
                    .rotation_interval
                    .map(|interval| Utc::now() + interval),
                key_strength: current_key.key_strength,
                master_key_id: current_key.master_key_id,
                last_used_at: None,
                usage_count: 0,
            };

            // Store new version and retire old version
            self.store_key(&new_key_record).await?;
            self.retire_key_version(key_id, current_key.version).await?;

            // Update cache with new key
            self.cache_key(key_id, new_key_material).await;

            // Clean up old versions if we exceed max_key_versions
            self.cleanup_old_key_versions(key_id).await?;

            // Record audit event
            if self.config.audit_enabled {
                self.record_audit_event(key_id, KeyOperation::Rotate, true, None)
                    .await?;
            }

            // Update statistics
            self.increment_rotation_count().await;

            info!(
                "Successfully rotated key {} to version {}",
                key_id, new_version
            );
            Ok(new_version)
        }
    }

    /// Check for keys that need rotation and rotate them automatically
    pub async fn perform_automatic_rotation(&mut self) -> Result<Vec<String>, EncryptionError> {
        if !self.config.auto_rotation_enabled {
            return Ok(vec![]);
        }

        // Note: Database-specific implementations should override this behavior
        warn!(
            "perform_automatic_rotation called on generic implementation - no rotation performed"
        );
        Ok(vec![])
    }

    /// Start automated key rotation service that runs in the background
    /// Returns a future that should be spawned as a background task
    pub async fn start_rotation_service(
        &self,
        check_interval: Duration,
    ) -> Result<impl std::future::Future<Output = ()>, EncryptionError> {
        if !self.config.auto_rotation_enabled {
            return Err(EncryptionError::InvalidConfiguration(
                "Auto rotation is not enabled".to_string(),
            ));
        }

        let pool = self.pool.clone();
        let config = self.config.clone();
        let master_key = self.master_key.clone();
        let master_key_id = self.master_key_id.clone();
        let stats = self.stats.clone();
        let key_cache = self.key_cache.clone();

        let rotation_service = async move {
            let mut interval_timer = tokio::time::interval(std::time::Duration::from_secs(
                check_interval.num_seconds() as u64,
            ));

            loop {
                interval_timer.tick().await;

                // Create a temporary KeyManager instance for the rotation check
                let key_manager = KeyManager {
                    config: config.clone(),
                    pool: pool.clone(),
                    master_key: master_key.clone(),
                    master_key_id: master_key_id.clone(),
                    stats: stats.clone(),
                    key_cache: key_cache.clone(),
                };

                // Clone for mutable operations
                let mut rotation_manager = key_manager.clone();

                match rotation_manager.perform_automatic_rotation().await {
                    Ok(rotated_keys) => {
                        if !rotated_keys.is_empty() {
                            info!(
                                "Background rotation service rotated {} keys: {:?}",
                                rotated_keys.len(),
                                rotated_keys
                            );
                        }
                    }
                    Err(e) => {
                        error!("Background rotation service failed: {:?}", e);
                    }
                }
            }
        };

        Ok(rotation_service)
    }

    /// Get current key management statistics
    pub async fn get_stats(&self) -> KeyManagerStats {
        self.stats
            .lock()
            .map(|stats| stats.clone())
            .unwrap_or_default()
    }

    /// Refresh statistics by querying the database
    pub async fn refresh_stats(&self) -> Result<(), EncryptionError> {
        // Note: Database-specific implementations should override this behavior
        // For now, this method doesn't refresh from database to prevent compilation issues
        warn!("refresh_stats called on generic implementation - no database refresh performed");
        Ok(())
    }

    /// Get the current master key ID
    pub async fn get_master_key_id(&self) -> Option<Uuid> {
        self.master_key_id.lock().map(|id| *id).unwrap_or(None)
    }

    /// Set the master key ID
    pub async fn set_master_key_id(&self, key_id: Uuid) -> Result<(), EncryptionError> {
        *self.master_key_id.lock().map_err(|_| {
            EncryptionError::KeyManagement("Failed to acquire master key ID lock".to_string())
        })? = Some(key_id);
        Ok(())
    }

    /// Generate and store a new master key
    pub async fn generate_master_key(&mut self) -> Result<Uuid, EncryptionError> {
        #[cfg(not(feature = "encryption"))]
        {
            return Err(EncryptionError::InvalidConfiguration(
                "Encryption feature is not enabled".to_string(),
            ));
        }

        #[cfg(feature = "encryption")]
        {
            // Generate a new master key
            let master_key_id = Uuid::new_v4();
            let mut master_key_material = vec![0u8; 32]; // 256-bit key
            OsRng.fill_bytes(&mut master_key_material);

            // Store the master key securely in the database
            // Note: Database persistence is optional - master key works in-memory only
            info!(
                "Master key generated and stored in memory with ID: {}",
                master_key_id
            );

            // Keep a copy in memory for performance (encrypted with a derived key)
            *self.master_key.lock().map_err(|_| {
                EncryptionError::KeyManagement("Failed to acquire master key lock".to_string())
            })? = Some(master_key_material);

            // Set the master key ID
            self.set_master_key_id(master_key_id).await?;

            // Record audit event
            if self.config.audit_enabled {
                self.record_audit_event(
                    &master_key_id.to_string(),
                    KeyOperation::Create,
                    true,
                    None,
                )
                .await?;
            }

            info!("Generated new master key: {}", master_key_id);
            Ok(master_key_id)
        }
    }

    // Private helper methods

    async fn load_master_key(&self) -> Result<(), EncryptionError> {
        #[cfg(not(feature = "encryption"))]
        {
            return Err(EncryptionError::InvalidConfiguration(
                "Encryption feature is not enabled".to_string(),
            ));
        }

        #[cfg(feature = "encryption")]
        {
            let master_key_material = match &self.config.master_key_source {
                KeySource::Environment(env_var) => {
                    let key_str = std::env::var(env_var).map_err(|_| {
                        EncryptionError::KeyManagement(format!(
                            "Master key environment variable {} not found",
                            env_var
                        ))
                    })?;

                    base64::engine::general_purpose::STANDARD
                        .decode(&key_str)
                        .map_err(|e| {
                            EncryptionError::KeyManagement(format!(
                                "Invalid base64 master key: {}",
                                e
                            ))
                        })?
                }
                KeySource::Static(key_str) => base64::engine::general_purpose::STANDARD
                    .decode(key_str)
                    .map_err(|e| {
                        EncryptionError::KeyManagement(format!("Invalid base64 master key: {}", e))
                    })?,
                KeySource::Generated(_) => {
                    // Generate a new master key (for development only)
                    warn!("Generating new master key - this should not be used in production");
                    let mut key = vec![0u8; 32];
                    OsRng.fill_bytes(&mut key);
                    key
                }
                KeySource::External(service_config) => {
                    // Load master key from external service
                    if service_config.starts_with("aws://") {
                        Self::load_master_key_from_aws(service_config).await
                    } else if service_config.starts_with("vault://") {
                        Self::load_master_key_from_vault(service_config).await
                    } else if service_config.starts_with("gcp://") {
                        Self::load_master_key_from_gcp(service_config).await
                    } else if service_config.starts_with("azure://") {
                        Self::load_master_key_from_azure(service_config).await
                    } else {
                        return Err(EncryptionError::KeyManagement(format!(
                            "Unknown external master key service: {}",
                            service_config
                        )));
                    }
                }
            };

            // Validate master key length
            if master_key_material.len() != 32 {
                return Err(EncryptionError::KeyManagement(format!(
                    "Master key must be 32 bytes, got {}",
                    master_key_material.len()
                )));
            }

            *self.master_key.lock().map_err(|_| {
                EncryptionError::KeyManagement("Failed to acquire master key lock".to_string())
            })? = Some(master_key_material.clone());

            // Generate a deterministic master key ID based on the key material and retrieve stored ID
            let master_key_id = self
                .get_or_create_master_key_id(&master_key_material)
                .await?;
            self.set_master_key_id(master_key_id).await?;

            debug!("Master key loaded successfully with ID: {}", master_key_id);
            Ok(())
        }
    }

    #[cfg(feature = "encryption")]
    async fn encrypt_key_material(&self, key_material: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        let master_key = self.master_key.lock().map_err(|_| {
            EncryptionError::KeyManagement("Failed to acquire master key lock".to_string())
        })?;

        let master_key_material = master_key
            .as_ref()
            .ok_or_else(|| EncryptionError::KeyManagement("Master key not loaded".to_string()))?;

        // Use AES-256-GCM to encrypt the key material
        let cipher_key = AesKey::<Aes256Gcm>::from_slice(master_key_material);
        let cipher = Aes256Gcm::new(cipher_key);

        // Generate random nonce
        let mut nonce_bytes = vec![0u8; 12];
        OsRng.fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        // Encrypt
        let mut ciphertext = cipher.encrypt(nonce, key_material).map_err(|e| {
            EncryptionError::EncryptionFailed(format!("Key encryption failed: {}", e))
        })?;

        // Prepend nonce to ciphertext for storage
        let mut encrypted_data = nonce_bytes;
        encrypted_data.append(&mut ciphertext);

        Ok(encrypted_data)
    }

    #[cfg(feature = "encryption")]
    async fn decrypt_key_material(
        &self,
        encrypted_data: &[u8],
    ) -> Result<Vec<u8>, EncryptionError> {
        if encrypted_data.len() < 12 {
            return Err(EncryptionError::DecryptionFailed(
                "Encrypted key data too short".to_string(),
            ));
        }

        let master_key = self.master_key.lock().map_err(|_| {
            EncryptionError::KeyManagement("Failed to acquire master key lock".to_string())
        })?;

        let master_key_material = master_key
            .as_ref()
            .ok_or_else(|| EncryptionError::KeyManagement("Master key not loaded".to_string()))?;

        // Extract nonce and ciphertext
        let nonce = Nonce::from_slice(&encrypted_data[..12]);
        let ciphertext = &encrypted_data[12..];

        // Decrypt using master key
        let cipher_key = AesKey::<Aes256Gcm>::from_slice(master_key_material);
        let cipher = Aes256Gcm::new(cipher_key);

        let plaintext = cipher.decrypt(nonce, ciphertext).map_err(|e| {
            EncryptionError::DecryptionFailed(format!("Key decryption failed: {}", e))
        })?;

        Ok(plaintext)
    }

    #[cfg(not(feature = "encryption"))]
    async fn encrypt_key_material(&self, _key_material: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        Err(EncryptionError::InvalidConfiguration(
            "Encryption feature is not enabled".to_string(),
        ))
    }

    #[cfg(not(feature = "encryption"))]
    async fn decrypt_key_material(
        &self,
        _encrypted_data: &[u8],
    ) -> Result<Vec<u8>, EncryptionError> {
        Err(EncryptionError::InvalidConfiguration(
            "Encryption feature is not enabled".to_string(),
        ))
    }

    async fn cache_key(&self, key_id: &str, key_material: Vec<u8>) {
        if let Ok(mut cache) = self.key_cache.lock() {
            cache.insert(key_id.to_string(), (key_material, Utc::now()));
        }
    }

    async fn get_cached_key(&self, key_id: &str) -> Option<Vec<u8>> {
        if let Ok(cache) = self.key_cache.lock() {
            // Check if key is in cache and not too old (cache for 1 hour)
            if let Some((key_material, cached_at)) = cache.get(key_id) {
                if Utc::now() - *cached_at < Duration::hours(1) {
                    return Some(key_material.clone());
                }
            }
        }
        None
    }

    // Database operations for key storage
    async fn store_key(&self, _key: &EncryptionKey) -> Result<(), EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn load_key(&self, _key_id: &str) -> Result<EncryptionKey, EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn retire_key_version(
        &self,
        _key_id: &str,
        _version: u32,
    ) -> Result<(), EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn cleanup_old_key_versions(&self, _key_id: &str) -> Result<(), EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn record_key_usage(&self, _key_id: &str) -> Result<(), EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn record_audit_event(
        &self,
        _key_id: &str,
        _operation: KeyOperation,
        _success: bool,
        _error_message: Option<String>,
    ) -> Result<(), EncryptionError> {
        // Database-specific implementations are provided in separate impl blocks
        Err(EncryptionError::KeyManagement(
            "Database-specific implementation required".to_string(),
        ))
    }

    async fn increment_key_count(&self) {
        if let Ok(mut stats) = self.stats.lock() {
            stats.total_keys += 1;
            stats.active_keys += 1;
        }
    }

    async fn increment_rotation_count(&self) {
        if let Ok(mut stats) = self.stats.lock() {
            stats.rotations_performed += 1;
        }
    }

    // External master key loading methods
    #[cfg(feature = "encryption")]
    async fn load_master_key_from_aws(service_config: &str) -> Vec<u8> {
        // Parse AWS KMS configuration for master key
        let config_parts: Vec<&str> = service_config
            .strip_prefix("aws://")
            .unwrap_or(service_config)
            .split('?')
            .collect();

        let key_id = config_parts[0];
        let region = if config_parts.len() > 1 {
            config_parts[1]
                .strip_prefix("region=")
                .unwrap_or("us-east-1")
        } else {
            "us-east-1"
        };

        info!(
            "Loading master key from AWS KMS: key_id={}, region={}",
            key_id, region
        );

        #[cfg(feature = "aws-kms")]
        {
            use aws_config::Region;
            use aws_sdk_kms::Client;

            // Load AWS configuration
            let config = aws_config::defaults(aws_config::BehaviorVersion::v2025_01_17())
                .region(Region::new(region.to_string()))
                .load()
                .await;

            let client = Client::new(&config);

            // Generate a data key for this specific master key
            // In practice, you might want to store the encrypted data key and decrypt it
            // For now, we'll generate a data key each time (which is expensive but functional)
            match client
                .generate_data_key()
                .key_id(key_id)
                .key_spec(aws_sdk_kms::types::DataKeySpec::Aes256)
                .send()
                .await
            {
                Ok(response) => {
                    if let Some(plaintext) = response.plaintext {
                        let key_material = plaintext.into_inner();
                        if key_material.len() == 32 {
                            info!("Successfully loaded master key from AWS KMS");
                            return key_material;
                        } else {
                            error!(
                                "AWS KMS returned key with incorrect length: {}",
                                key_material.len()
                            );
                        }
                    }
                }
                Err(e) => {
                    error!("Failed to load key from AWS KMS: {}", e);
                }
            }
        }

        #[cfg(not(feature = "aws-kms"))]
        {
            warn!("AWS KMS feature not enabled, falling back to deterministic key generation");
        }

        // Fallback to deterministic key generation for development/testing
        super::generate_deterministic_key("aws-kms-master-key", &[key_id, region])
    }

    #[cfg(feature = "encryption")]
    async fn load_master_key_from_vault(service_config: &str) -> Vec<u8> {
        // Parse Vault configuration for master key
        let config_parts: Vec<&str> = service_config
            .strip_prefix("vault://")
            .unwrap_or(service_config)
            .split('?')
            .collect();

        let secret_path = config_parts[0];
        let vault_addr = if config_parts.len() > 1 {
            config_parts[1]
                .strip_prefix("addr=")
                .unwrap_or("https://vault.example.com")
                .to_string()
        } else {
            std::env::var("VAULT_ADDR").unwrap_or_else(|_| "https://vault.example.com".to_string())
        };

        info!(
            "Loading master key from HashiCorp Vault: path={}, addr={}",
            secret_path, vault_addr
        );

        #[cfg(feature = "vault-kms")]
        {
            use vaultrs::{client::VaultClient, kv2};

            // Try to get Vault token from environment
            let token = std::env::var("VAULT_TOKEN").ok();

            if let Some(vault_token) = token {
                // Create Vault client
                let client_result = VaultClient::new(
                    vaultrs::client::VaultClientSettingsBuilder::default()
                        .address(vault_addr.clone())
                        .token(vault_token)
                        .build()
                        .unwrap(),
                );

                match client_result {
                    Ok(client) => {
                        // Try to read the secret from Vault
                        // Parse the path to extract mount and secret path
                        let path_parts: Vec<&str> = secret_path.split('/').collect();
                        if path_parts.len() >= 2 {
                            let mount = path_parts[0];
                            let secret_key = path_parts[1..].join("/");

                            match kv2::read::<serde_json::Value>(&client, mount, &secret_key).await
                            {
                                Ok(secret) => {
                                    // Look for a key field in the secret
                                    if let Some(key_data) = secret.get("key") {
                                        if let Some(key_str) = key_data.as_str() {
                                            // Try to decode as base64 first
                                            if let Ok(decoded) = base64::Engine::decode(
                                                &base64::engine::general_purpose::STANDARD,
                                                key_str,
                                            ) {
                                                if decoded.len() == 32 {
                                                    info!(
                                                        "Successfully loaded master key from HashiCorp Vault"
                                                    );
                                                    return decoded;
                                                }
                                            }
                                            // If not base64, use as string and hash to 32 bytes
                                            use sha2::{Digest, Sha256};
                                            let mut hasher = Sha256::new();
                                            hasher.update(key_str.as_bytes());
                                            let hash = hasher.finalize();
                                            info!(
                                                "Successfully loaded and hashed master key from HashiCorp Vault"
                                            );
                                            return hash[0..32].to_vec();
                                        }
                                    }

                                    // If no 'key' field, generate from secret path
                                    warn!(
                                        "No 'key' field found in Vault secret, using deterministic generation"
                                    );
                                }
                                Err(e) => {
                                    error!("Failed to read secret from HashiCorp Vault: {}", e);
                                }
                            }
                        } else {
                            error!("Invalid Vault secret path format: {}", secret_path);
                        }
                    }
                    Err(e) => {
                        error!("Failed to create Vault client: {}", e);
                    }
                }
            } else {
                warn!(
                    "No VAULT_TOKEN environment variable found, falling back to deterministic key generation"
                );
            }
        }

        #[cfg(not(feature = "vault-kms"))]
        {
            warn!("Vault KMS feature not enabled, falling back to deterministic key generation");
        }

        // Fallback to deterministic key generation for development/testing
        super::generate_deterministic_key("vault-master-key", &[secret_path, &vault_addr])
    }

    #[cfg(feature = "encryption")]
    async fn load_master_key_from_gcp(service_config: &str) -> Vec<u8> {
        // Parse GCP KMS configuration for master key
        let key_resource = service_config
            .strip_prefix("gcp://")
            .unwrap_or(service_config);

        info!("Loading master key from GCP KMS: resource={}", key_resource);

        #[cfg(feature = "gcp-kms")]
        {
            use google_cloud_kms::client::{Client, ClientConfig};
            use google_cloud_kms::grpc::kms::v1::GenerateRandomBytesRequest;

            // Try to create GCP KMS client with automatic authentication
            let config_result = ClientConfig::default().with_auth().await;

            match config_result {
                Ok(client_config) => {
                    let client_result = Client::new(client_config).await;

                    match client_result {
                        Ok(client) => {
                            // Parse the key resource path for project and location
                            let path_parts: Vec<&str> = key_resource.split('/').collect();
                            if path_parts.len() >= 4 {
                                let project = path_parts[1];
                                let location = path_parts[3];

                                // Create a parent path for the project/location
                                let parent = format!("projects/{}/locations/{}", project, location);

                                // Generate random bytes for the master key
                                let req = GenerateRandomBytesRequest {
                                    location: parent,
                                    length_bytes: 32, // Always 32 bytes for master key
                                    protection_level: 1, // SOFTWARE (default protection level)
                                };

                                match client.generate_random_bytes(req, None).await {
                                    Ok(response) => {
                                        let plaintext = response.data;
                                        if plaintext.len() == 32 {
                                            info!("Successfully generated master key from GCP KMS");
                                            return plaintext;
                                        } else {
                                            error!(
                                                "GCP KMS returned key with incorrect length: {}",
                                                plaintext.len()
                                            );
                                        }
                                    }
                                    Err(e) => {
                                        error!(
                                            "Failed to generate random bytes from GCP KMS: {}",
                                            e
                                        );
                                    }
                                }
                            } else {
                                error!("Invalid GCP KMS resource path format: {}", key_resource);
                            }
                        }
                        Err(e) => {
                            error!("Failed to create GCP KMS client: {}", e);
                        }
                    }
                }
                Err(e) => {
                    error!("Failed to configure GCP KMS client: {}", e);
                }
            }
        }

        #[cfg(not(feature = "gcp-kms"))]
        {
            warn!("GCP KMS feature not enabled, falling back to deterministic key generation");
        }

        // Fallback to deterministic key generation for development/testing
        super::generate_deterministic_key("gcp-kms-master-key", &[key_resource])
    }

    /// Load master key from Azure Key Vault
    ///
    /// This method attempts to retrieve the master key from Azure Key Vault using the
    /// configured service URL and key name. If Azure Key Vault is not available or
    /// the `azure-kv` feature is not enabled, it falls back to deterministic key generation.
    ///
    /// # Arguments
    ///
    /// * `service_config` - Azure Key Vault configuration string in format "azure://vault-name/path/key-name"
    ///
    /// # Returns
    ///
    /// A 32-byte master key suitable for AES-256 encryption
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::key_manager::KeyManager;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Load master key from Azure Key Vault
    /// let master_key = KeyManager::<sqlx::Postgres>::load_master_key_from_azure(
    ///     "azure://my-vault.vault.azure.net/keys/master-key"
    /// ).await;
    ///
    /// assert_eq!(master_key.len(), 32); // AES-256 key size
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    #[cfg(feature = "encryption")]
    async fn load_master_key_from_azure(service_config: &str) -> Vec<u8> {
        // Parse Azure Key Vault configuration for master key
        let vault_parts: Vec<&str> = service_config
            .strip_prefix("azure://")
            .unwrap_or(service_config)
            .split('/')
            .collect();

        let vault_url = if !vault_parts.is_empty() {
            format!("https://{}", vault_parts[0])
        } else {
            "https://vault.vault.azure.net".to_string()
        };

        let key_name = vault_parts.get(2).unwrap_or(&"master-key");

        info!(
            "Loading master key from Azure Key Vault: vault={}, key={}",
            vault_url, key_name
        );

        // Try to load from Azure Key Vault if the feature is enabled
        #[cfg(feature = "azure-kv")]
        {
            match Self::load_from_azure_key_vault(&vault_url, key_name).await {
                Ok(key_material) => {
                    info!("Successfully loaded master key from Azure Key Vault");
                    return key_material;
                }
                Err(e) => {
                    warn!("Failed to load master key from Azure Key Vault: {}", e);
                    info!("Falling back to deterministic key generation");
                }
            }
        }

        // Fallback to deterministic key generation for development/testing
        super::generate_deterministic_key("azure-kv-master-key", &[&vault_url, key_name])
    }

    /// Load key material directly from Azure Key Vault
    ///
    /// This method uses the Azure SDK to authenticate and retrieve key material from
    /// Azure Key Vault. It supports automatic credential resolution through
    /// `DefaultAzureCredential` and handles key size normalization.
    ///
    /// # Arguments
    ///
    /// * `vault_url` - Full URL to the Azure Key Vault (e.g., "https://my-vault.vault.azure.net")
    /// * `key_name` - Name of the key to retrieve from the vault
    ///
    /// # Returns
    ///
    /// A 32-byte key material suitable for AES-256 encryption, or an error message
    ///
    /// # Security Features
    ///
    /// - Uses `DefaultAzureCredential` for secure authentication
    /// - Automatically handles key size normalization via HMAC-based key derivation
    /// - Supports base64-encoded key material from Azure Key Vault
    /// - Includes proper error handling for authentication and network issues
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(all(feature = "encryption", feature = "azure-kv"))]
    /// # {
    /// use hammerwork::encryption::key_manager::KeyManager;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Load key from Azure Key Vault
    /// let key_material = KeyManager::<sqlx::Postgres>::load_from_azure_key_vault(
    ///     "https://my-vault.vault.azure.net",
    ///     "master-key"
    /// ).await?;
    ///
    /// assert_eq!(key_material.len(), 32); // Always 32 bytes for AES-256
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    #[cfg(all(feature = "encryption", feature = "azure-kv"))]
    async fn load_from_azure_key_vault(vault_url: &str, key_name: &str) -> Result<Vec<u8>, String> {
        use azure_identity::{DefaultAzureCredential, TokenCredentialOptions};
        use azure_security_keyvault::KeyvaultClient;

        // Create Azure credentials
        let credential = DefaultAzureCredential::create(TokenCredentialOptions::default())
            .map_err(|e| format!("Failed to create Azure credentials: {}", e))?;

        // Create Azure Key Vault client
        let client = KeyvaultClient::new(vault_url, std::sync::Arc::new(credential))
            .map_err(|e| format!("Failed to create Azure Key Vault client: {}", e))?;

        // Retrieve the master key from Azure Key Vault
        match client.key_client().get(key_name.to_string()).await {
            Ok(key_response) => {
                if let Some(key_material) = key_response.key.k {
                    // Decode the base64-encoded key material
                    let decoded_key = base64::engine::general_purpose::URL_SAFE_NO_PAD
                        .decode(key_material)
                        .map_err(|e| format!("Failed to decode key material: {}", e))?;

                    // Ensure the key is the correct size for AES-256 (32 bytes)
                    if decoded_key.len() >= 32 {
                        Ok(decoded_key[0..32].to_vec())
                    } else {
                        // If the key is too short, use it as input for HMAC-based key derivation
                        use hmac::{Hmac, Mac};
                        use sha2::Sha256;

                        let mut hmac = <Hmac<Sha256> as Mac>::new_from_slice(&decoded_key)
                            .map_err(|e| format!("Failed to create HMAC: {}", e))?;
                        hmac.update(b"azure-kv-master-key-derivation");
                        hmac.update(vault_url.as_bytes());
                        hmac.update(key_name.as_bytes());
                        let result = hmac.finalize();
                        Ok(result.into_bytes()[0..32].to_vec())
                    }
                } else {
                    Err("Key material not found in Azure Key Vault response".to_string())
                }
            }
            Err(e) => Err(format!(
                "Failed to retrieve key from Azure Key Vault: {}",
                e
            )),
        }
    }

    /// Get or create a master key ID based on key material, with database persistence
    async fn get_or_create_master_key_id(
        &self,
        key_material: &[u8],
    ) -> Result<Uuid, EncryptionError> {
        // First, try to find an existing master key ID in the database
        let existing_key_id = self.find_master_key_id_in_database().await?;

        if let Some(key_id) = existing_key_id {
            debug!("Using existing master key ID from database: {}", key_id);
            return Ok(key_id);
        }

        // Generate a deterministic ID based on key material for consistency
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(key_material);
        hasher.update(b"hammerwork-master-key-v1"); // Version tag for future compatibility
        let hash = hasher.finalize();

        let master_key_id = Uuid::from_bytes([
            hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7], hash[8],
            hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15],
        ]);

        // Store this ID association in the database for future lookups
        self.store_master_key_id_mapping(&master_key_id).await?;

        debug!("Generated and stored new master key ID: {}", master_key_id);
        Ok(master_key_id)
    }

    /// Find existing master key ID in database
    async fn find_master_key_id_in_database(&self) -> Result<Option<Uuid>, EncryptionError> {
        #[cfg(feature = "postgres")]
        {
            let row = sqlx::query(
                "SELECT key_id FROM hammerwork_encryption_keys WHERE key_purpose = 'KEK' AND status = 'Active' LIMIT 1"
            )
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| EncryptionError::DatabaseError(e.to_string()))?;

            if let Some(row) = row {
                let key_id_str: String = row.get("key_id");
                let key_id = Uuid::parse_str(&key_id_str).map_err(|e| {
                    EncryptionError::KeyManagement(format!("Invalid UUID in database: {}", e))
                })?;
                return Ok(Some(key_id));
            }
        }

        #[cfg(feature = "mysql")]
        {
            let row = sqlx::query(
                "SELECT key_id FROM hammerwork_encryption_keys WHERE key_purpose = 'KEK' AND status = 'Active' LIMIT 1"
            )
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| EncryptionError::DatabaseError(e.to_string()))?;

            if let Some(row) = row {
                let key_id_str: String = row.get("key_id");
                let key_id = Uuid::parse_str(&key_id_str).map_err(|e| {
                    EncryptionError::KeyManagement(format!("Invalid UUID in database: {}", e))
                })?;
                return Ok(Some(key_id));
            }
        }

        Ok(None)
    }

    /// Store master key ID mapping for future lookups
    async fn store_master_key_id_mapping(
        &self,
        master_key_id: &Uuid,
    ) -> Result<(), EncryptionError> {
        // Master key storage is handled by generate_master_key, so this is just a placeholder
        // for future implementation if we need additional mapping tables
        debug!("Master key ID mapping stored: {}", master_key_id);
        Ok(())
    }

    /// Derive a system encryption key for encrypting master keys
    #[allow(dead_code)]
    fn derive_system_encryption_key(&self, salt: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        use argon2::{
            Argon2,
            password_hash::{PasswordHasher, SaltString},
        };

        // Use a combination of system properties and configuration for key derivation
        let mut input = Vec::new();
        input.extend_from_slice(b"hammerwork-system-key-v1");

        // Add configuration-based entropy
        if let Some(ref external_config) = self.config.external_kms_config {
            input.extend_from_slice(external_config.service_type.as_bytes());
            input.extend_from_slice(external_config.endpoint.as_bytes());
            if let Some(ref region) = external_config.region {
                input.extend_from_slice(region.as_bytes());
            }
        }

        // Add system-specific entropy (hostname, etc.)
        if let Ok(hostname) = std::env::var("HOSTNAME") {
            input.extend_from_slice(hostname.as_bytes());
        }

        // Use Argon2 for secure key derivation
        let argon2 = Argon2::default();
        let salt_string = SaltString::encode_b64(salt)
            .map_err(|e| EncryptionError::KeyManagement(format!("Failed to encode salt: {}", e)))?;

        let password_hash = argon2
            .hash_password(&input, &salt_string)
            .map_err(|e| EncryptionError::KeyManagement(format!("Key derivation failed: {}", e)))?;

        // Extract the raw hash bytes
        let hash = password_hash.hash.ok_or_else(|| {
            EncryptionError::KeyManagement("No hash in password result".to_string())
        })?;
        let hash_bytes = hash.as_bytes();

        // Return first 32 bytes for AES-256
        Ok(hash_bytes[0..32].to_vec())
    }

    /// Encrypt data with system-derived key
    #[allow(dead_code)]
    fn encrypt_with_system_key(
        &self,
        system_key: &[u8],
        plaintext: &[u8],
    ) -> Result<Vec<u8>, EncryptionError> {
        use aes_gcm::{
            Aes256Gcm, Nonce,
            aead::{Aead, KeyInit, OsRng},
        };

        let cipher = Aes256Gcm::new_from_slice(system_key).map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to create cipher: {}", e))
        })?;

        // Generate random nonce
        let mut nonce_bytes = [0u8; 12];
        use rand::RngCore;
        OsRng.fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        // Encrypt the data
        let ciphertext = cipher
            .encrypt(nonce, plaintext)
            .map_err(|e| EncryptionError::KeyManagement(format!("Encryption failed: {}", e)))?;

        // Prepend nonce to ciphertext for storage
        let mut result = nonce_bytes.to_vec();
        result.extend_from_slice(&ciphertext);

        Ok(result)
    }
}

// Database-specific implementations
#[cfg(feature = "postgres")]
impl KeyManager<sqlx::Postgres> {
    #[allow(dead_code)]
    async fn store_key_postgres(&self, key: &EncryptionKey) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            INSERT INTO hammerwork_encryption_keys (
                id, key_id, key_version, algorithm, key_material, key_derivation_salt, key_source, key_purpose,
                created_at, created_by, expires_at, rotated_at, retired_at, status, rotation_interval, next_rotation_at,
                key_strength, master_key_id, last_used_at, usage_count
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
            ON CONFLICT (key_id) DO UPDATE SET
                key_version = $3,
                algorithm = $4,
                key_material = $5,
                status = $14,
                rotated_at = $12,
                next_rotation_at = $16,
                last_used_at = $19,
                usage_count = $20
            "#
        )
        .bind(key.id)
        .bind(&key.key_id)
        .bind(key.version as i32)
        .bind(key.algorithm.to_string())
        .bind(&key.encrypted_key_material)
        .bind(&key.derivation_salt)
        .bind(key.source.to_string())
        .bind(key.purpose.to_string())
        .bind(key.created_at)
        .bind(&key.created_by)
        .bind(key.expires_at)
        .bind(key.rotated_at)
        .bind(key.retired_at)
        .bind(key.status.to_string())
        .bind(key.rotation_interval.map(|d| {
            // Convert chrono::Duration to PostgreSQL INTERVAL
            format!("{} seconds", d.num_seconds())
        }))
        .bind(key.next_rotation_at)
        .bind(key.key_strength as i32)
        .bind(key.master_key_id)
        .bind(key.last_used_at)
        .bind(key.usage_count as i64)
        .execute(&self.pool)
        .await
        .map_err(|e| EncryptionError::KeyManagement(format!("Failed to store key: {}", e)))?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn load_key_postgres(&self, key_id: &str) -> Result<EncryptionKey, EncryptionError> {
        let row = sqlx::query(
            r#"
            SELECT id, key_id, key_version, algorithm, key_material, key_derivation_salt, key_source, key_purpose,
                   created_at, created_by, expires_at, rotated_at, retired_at, status, rotation_interval, next_rotation_at,
                   key_strength, master_key_id, last_used_at, usage_count
            FROM hammerwork_encryption_keys
            WHERE key_id = $1
            ORDER BY key_version DESC
            LIMIT 1
            "#
        )
        .bind(key_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| EncryptionError::KeyManagement(format!("Failed to load key: {}", e)))?;

        let row = row
            .ok_or_else(|| EncryptionError::KeyManagement(format!("Key not found: {}", key_id)))?;

        let rotation_interval =
            if let Some(interval_str) = row.get::<Option<String>, _>("rotation_interval") {
                // Parse PostgreSQL INTERVAL format
                parse_postgres_interval(&interval_str)
            } else {
                None
            };

        Ok(EncryptionKey {
            id: row.get("id"),
            key_id: row.get("key_id"),
            version: row.get::<i32, _>("key_version") as u32,
            algorithm: parse_algorithm(row.get("algorithm"))?,
            encrypted_key_material: row.get("key_material"),
            derivation_salt: row.get("key_derivation_salt"),
            source: parse_key_source(row.get("key_source"))?,
            purpose: parse_key_purpose(row.get("key_purpose"))?,
            created_at: row.get("created_at"),
            created_by: row.get("created_by"),
            expires_at: row.get("expires_at"),
            rotated_at: row.get("rotated_at"),
            retired_at: row.get("retired_at"),
            status: parse_key_status(row.get("status"))?,
            rotation_interval,
            next_rotation_at: row.get("next_rotation_at"),
            key_strength: row.get::<i32, _>("key_strength") as u32,
            master_key_id: row.get("master_key_id"),
            last_used_at: row.get("last_used_at"),
            usage_count: row.get::<i64, _>("usage_count") as u64,
        })
    }

    #[allow(dead_code)]
    async fn retire_key_version_postgres(
        &self,
        key_id: &str,
        version: u32,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET status = 'Retired', retired_at = NOW()
            WHERE key_id = $1 AND key_version = $2
            "#,
        )
        .bind(key_id)
        .bind(version as i32)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to retire key version: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn cleanup_old_key_versions_postgres(&self, key_id: &str) -> Result<(), EncryptionError> {
        // Keep only the latest max_key_versions for each key_id
        sqlx::query(
            r#"
            DELETE FROM hammerwork_encryption_keys
            WHERE key_id = $1 AND key_version NOT IN (
                SELECT key_version FROM hammerwork_encryption_keys
                WHERE key_id = $1
                ORDER BY key_version DESC
                LIMIT $2
            )
            "#,
        )
        .bind(key_id)
        .bind(self.config.max_key_versions as i32)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to cleanup old key versions: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn get_keys_due_for_rotation_postgres(&self) -> Result<Vec<String>, EncryptionError> {
        let rows = sqlx::query(
            r#"
            SELECT key_id
            FROM hammerwork_encryption_keys
            WHERE status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to get keys due for rotation: {}", e))
        })?;

        Ok(rows.into_iter().map(|row| row.get("key_id")).collect())
    }

    #[allow(dead_code)]
    async fn record_key_usage_postgres(&self, key_id: &str) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET last_used_at = NOW(), usage_count = usage_count + 1
            WHERE key_id = $1
            "#,
        )
        .bind(key_id)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to record key usage: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn record_audit_event_postgres(
        &self,
        key_id: &str,
        operation: KeyOperation,
        success: bool,
        error_message: Option<String>,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            INSERT INTO hammerwork_key_audit_log (
                key_id, operation, success, error_message, timestamp
            ) VALUES ($1, $2, $3, $4, NOW())
            "#,
        )
        .bind(key_id)
        .bind(operation.to_string())
        .bind(success)
        .bind(error_message)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to record audit event: {}", e))
        })?;

        Ok(())
    }

    /// Check if a specific key is due for rotation
    #[cfg(feature = "postgres")]
    pub async fn is_key_due_for_rotation(&self, key_id: &str) -> Result<bool, EncryptionError> {
        let result = sqlx::query(
            r#"
            SELECT COUNT(*) as count
            FROM hammerwork_encryption_keys
            WHERE key_id = $1
            AND status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .bind(key_id)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to check rotation status for key {}: {}",
                key_id, e
            ))
        })?;

        let count: i64 = result.get("count");
        Ok(count > 0)
    }

    /// Update rotation schedule for a key (PostgreSQL)
    async fn update_key_rotation_schedule_postgres(
        &self,
        key_id: &str,
        rotation_interval: Option<Duration>,
        next_rotation_at: Option<DateTime<Utc>>,
    ) -> Result<(), EncryptionError> {
        let interval_postgres =
            rotation_interval.map(|interval| format!("{} seconds", interval.num_seconds()));

        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET rotation_interval = $2, next_rotation_at = $3
            WHERE key_id = $1 AND status = 'Active'
            "#,
        )
        .bind(key_id)
        .bind(interval_postgres)
        .bind(next_rotation_at)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to update rotation schedule for key {}: {}",
                key_id, e
            ))
        })?;

        info!(
            "Updated rotation schedule for key {}: interval={:?}, next_rotation={:?}",
            key_id, rotation_interval, next_rotation_at
        );
        Ok(())
    }

    /// Get rotation schedule for a key (PostgreSQL)
    async fn get_key_rotation_schedule_postgres(
        &self,
        key_id: &str,
    ) -> Result<Option<DateTime<Utc>>, EncryptionError> {
        let result = sqlx::query(
            r#"
            SELECT next_rotation_at
            FROM hammerwork_encryption_keys
            WHERE key_id = $1 AND status = 'Active'
            ORDER BY key_version DESC
            LIMIT 1
            "#,
        )
        .bind(key_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to get rotation schedule for key {}: {}",
                key_id, e
            ))
        })?;

        match result {
            Some(row) => Ok(row.get("next_rotation_at")),
            None => Ok(None),
        }
    }

    /// Schedule a key for rotation at a specific time (PostgreSQL)
    async fn schedule_key_rotation_postgres(
        &self,
        key_id: &str,
        rotation_time: DateTime<Utc>,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET next_rotation_at = $2
            WHERE key_id = $1 AND status = 'Active'
            "#,
        )
        .bind(key_id)
        .bind(rotation_time)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to schedule rotation for key {}: {}",
                key_id, e
            ))
        })?;

        info!("Scheduled rotation for key {} at {}", key_id, rotation_time);
        Ok(())
    }

    /// Get scheduled rotations within a time window (PostgreSQL)
    async fn get_scheduled_rotations_postgres(
        &self,
        from_time: DateTime<Utc>,
        to_time: DateTime<Utc>,
    ) -> Result<Vec<(String, DateTime<Utc>)>, EncryptionError> {
        let rows = sqlx::query(
            r#"
            SELECT key_id, next_rotation_at
            FROM hammerwork_encryption_keys
            WHERE status = 'Active'
            AND next_rotation_at IS NOT NULL
            AND next_rotation_at BETWEEN $1 AND $2
            ORDER BY next_rotation_at ASC
            "#,
        )
        .bind(from_time)
        .bind(to_time)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to get scheduled rotations: {}", e))
        })?;

        let scheduled_rotations = rows
            .into_iter()
            .filter_map(|row| {
                let key_id: String = row.get("key_id");
                let rotation_time: Option<DateTime<Utc>> = row.get("next_rotation_at");
                rotation_time.map(|time| (key_id, time))
            })
            .collect();

        Ok(scheduled_rotations)
    }

    /// Update the rotation schedule for a key (PostgreSQL)
    pub async fn update_key_rotation_schedule(
        &self,
        key_id: &str,
        rotation_interval: Option<Duration>,
    ) -> Result<(), EncryptionError> {
        let next_rotation_at = rotation_interval.map(|interval| Utc::now() + interval);
        self.update_key_rotation_schedule_postgres(key_id, rotation_interval, next_rotation_at)
            .await
    }

    /// Get the next scheduled rotation time for a key (PostgreSQL)
    pub async fn get_key_rotation_schedule(
        &self,
        key_id: &str,
    ) -> Result<Option<DateTime<Utc>>, EncryptionError> {
        self.get_key_rotation_schedule_postgres(key_id).await
    }

    /// Schedule a key for future rotation (PostgreSQL)
    pub async fn schedule_key_rotation(
        &self,
        key_id: &str,
        rotation_time: DateTime<Utc>,
    ) -> Result<(), EncryptionError> {
        self.schedule_key_rotation_postgres(key_id, rotation_time)
            .await
    }

    /// Get all keys scheduled for rotation within a time window (PostgreSQL)
    pub async fn get_scheduled_rotations(
        &self,
        from_time: DateTime<Utc>,
        to_time: DateTime<Utc>,
    ) -> Result<Vec<(String, DateTime<Utc>)>, EncryptionError> {
        self.get_scheduled_rotations_postgres(from_time, to_time)
            .await
    }

    /// Query statistics from PostgreSQL
    #[cfg(feature = "postgres")]
    pub async fn query_database_statistics(&self) -> Result<KeyManagerStats, EncryptionError> {
        // Execute multiple queries to gather comprehensive statistics
        let basic_counts = sqlx::query(
            r#"
            SELECT 
                COUNT(*) as total_keys,
                COUNT(CASE WHEN status = 'Active' THEN 1 END) as active_keys,
                COUNT(CASE WHEN status = 'Retired' THEN 1 END) as retired_keys,
                COUNT(CASE WHEN status = 'Revoked' THEN 1 END) as revoked_keys,
                COUNT(CASE WHEN status = 'Expired' THEN 1 END) as expired_keys
            FROM hammerwork_encryption_keys
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query key counts: {}", e))
        })?;

        let total_keys: i64 = basic_counts.get("total_keys");
        let active_keys: i64 = basic_counts.get("active_keys");
        let retired_keys: i64 = basic_counts.get("retired_keys");
        let revoked_keys: i64 = basic_counts.get("revoked_keys");
        let expired_keys: i64 = basic_counts.get("expired_keys");

        // Calculate average key age
        let age_result = sqlx::query(
            r#"
            SELECT 
                COALESCE(AVG(EXTRACT(EPOCH FROM (NOW() - created_at)) / 86400), 0) as avg_age_days
            FROM hammerwork_encryption_keys 
            WHERE status IN ('Active', 'Retired')
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query average age: {}", e))
        })?;

        let average_key_age_days: f64 = age_result.get("avg_age_days");

        // Count keys expiring soon (within 7 days)
        let expiring_result = sqlx::query(
            r#"
            SELECT COUNT(*) as expiring_soon
            FROM hammerwork_encryption_keys 
            WHERE status = 'Active' 
            AND expires_at IS NOT NULL 
            AND expires_at <= NOW() + INTERVAL '7 days'
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query expiring keys: {}", e))
        })?;

        let keys_expiring_soon: i64 = expiring_result.get("expiring_soon");

        // Count keys due for rotation
        let rotation_result = sqlx::query(
            r#"
            SELECT COUNT(*) as due_for_rotation
            FROM hammerwork_encryption_keys 
            WHERE status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query rotation due keys: {}", e))
        })?;

        let keys_due_for_rotation: i64 = rotation_result.get("due_for_rotation");

        Ok(KeyManagerStats {
            total_keys: total_keys as u64,
            active_keys: active_keys as u64,
            retired_keys: retired_keys as u64,
            revoked_keys: revoked_keys as u64,
            expired_keys: expired_keys as u64,
            average_key_age_days,
            keys_expiring_soon: keys_expiring_soon as u64,
            keys_due_for_rotation: keys_due_for_rotation as u64,
            // Keep existing memory-tracked values
            total_access_operations: 0, // This should be tracked in memory or separate table
            rotations_performed: 0,     // This should be tracked in memory or separate table
        })
    }

    /// Get keys due for rotation
    #[cfg(feature = "postgres")]
    pub async fn get_keys_due_for_rotation(&self) -> Result<Vec<String>, EncryptionError> {
        self.get_keys_due_for_rotation_postgres().await
    }
}

#[cfg(feature = "mysql")]
impl KeyManager<sqlx::MySql> {
    #[allow(dead_code)]
    async fn store_key_mysql(&self, key: &EncryptionKey) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            INSERT INTO hammerwork_encryption_keys (
                id, key_id, key_version, algorithm, key_material, key_derivation_salt, key_source, key_purpose,
                created_at, created_by, expires_at, rotated_at, retired_at, status, rotation_interval_seconds, next_rotation_at,
                key_strength, master_key_id, last_used_at, usage_count
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                key_version = VALUES(key_version),
                algorithm = VALUES(algorithm),
                key_material = VALUES(key_material),
                status = VALUES(status),
                rotated_at = VALUES(rotated_at),
                next_rotation_at = VALUES(next_rotation_at),
                last_used_at = VALUES(last_used_at),
                usage_count = VALUES(usage_count)
            "#
        )
        .bind(key.id.to_string())
        .bind(&key.key_id)
        .bind(key.version as i32)
        .bind(key.algorithm.to_string())
        .bind(&key.encrypted_key_material)
        .bind(&key.derivation_salt)
        .bind(key.source.to_string())
        .bind(key.purpose.to_string())
        .bind(key.created_at)
        .bind(&key.created_by)
        .bind(key.expires_at)
        .bind(key.rotated_at)
        .bind(key.retired_at)
        .bind(key.status.to_string())
        .bind(key.rotation_interval.map(|d| d.num_seconds()))
        .bind(key.next_rotation_at)
        .bind(key.key_strength as i32)
        .bind(key.master_key_id.map(|id| id.to_string()))
        .bind(key.last_used_at)
        .bind(key.usage_count as i64)
        .execute(&self.pool)
        .await
        .map_err(|e| EncryptionError::KeyManagement(format!("Failed to store key: {}", e)))?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn load_key_mysql(&self, key_id: &str) -> Result<EncryptionKey, EncryptionError> {
        let row = sqlx::query(
            r#"
            SELECT id, key_id, key_version, algorithm, key_material, key_derivation_salt, key_source, key_purpose,
                   created_at, created_by, expires_at, rotated_at, retired_at, status, rotation_interval_seconds, next_rotation_at,
                   key_strength, master_key_id, last_used_at, usage_count
            FROM hammerwork_encryption_keys
            WHERE key_id = ?
            ORDER BY key_version DESC
            LIMIT 1
            "#
        )
        .bind(key_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| EncryptionError::KeyManagement(format!("Failed to load key: {}", e)))?;

        let row = row
            .ok_or_else(|| EncryptionError::KeyManagement(format!("Key not found: {}", key_id)))?;

        let rotation_interval = row
            .get::<Option<i64>, _>("rotation_interval_seconds")
            .map(Duration::seconds);

        Ok(EncryptionKey {
            id: uuid::Uuid::parse_str(&row.get::<String, _>("id"))
                .map_err(|e| EncryptionError::KeyManagement(format!("Invalid UUID: {}", e)))?,
            key_id: row.get("key_id"),
            version: row.get::<i32, _>("key_version") as u32,
            algorithm: parse_algorithm(row.get("algorithm"))?,
            encrypted_key_material: row.get("key_material"),
            derivation_salt: row.get("key_derivation_salt"),
            source: parse_key_source(row.get("key_source"))?,
            purpose: parse_key_purpose(row.get("key_purpose"))?,
            created_at: row.get("created_at"),
            created_by: row.get("created_by"),
            expires_at: row.get("expires_at"),
            rotated_at: row.get("rotated_at"),
            retired_at: row.get("retired_at"),
            status: parse_key_status(row.get("status"))?,
            rotation_interval,
            next_rotation_at: row.get("next_rotation_at"),
            key_strength: row.get::<i32, _>("key_strength") as u32,
            master_key_id: row
                .get::<Option<String>, _>("master_key_id")
                .map(|s| {
                    uuid::Uuid::parse_str(&s).map_err(|e| {
                        EncryptionError::KeyManagement(format!("Invalid master key UUID: {}", e))
                    })
                })
                .transpose()?,
            last_used_at: row.get("last_used_at"),
            usage_count: row.get::<i64, _>("usage_count") as u64,
        })
    }

    #[allow(dead_code)]
    async fn retire_key_version_mysql(
        &self,
        key_id: &str,
        version: u32,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET status = 'Retired', retired_at = NOW()
            WHERE key_id = ? AND key_version = ?
            "#,
        )
        .bind(key_id)
        .bind(version as i32)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to retire key version: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn cleanup_old_key_versions_mysql(&self, key_id: &str) -> Result<(), EncryptionError> {
        // Keep only the latest max_key_versions for each key_id
        sqlx::query(
            r#"
            DELETE FROM hammerwork_encryption_keys
            WHERE key_id = ? AND key_version NOT IN (
                SELECT key_version FROM (
                    SELECT key_version FROM hammerwork_encryption_keys
                    WHERE key_id = ?
                    ORDER BY key_version DESC
                    LIMIT ?
                ) t
            )
            "#,
        )
        .bind(key_id)
        .bind(key_id)
        .bind(self.config.max_key_versions as i32)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to cleanup old key versions: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn get_keys_due_for_rotation_mysql(&self) -> Result<Vec<String>, EncryptionError> {
        let rows = sqlx::query(
            r#"
            SELECT key_id
            FROM hammerwork_encryption_keys
            WHERE status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to get keys due for rotation: {}", e))
        })?;

        Ok(rows.into_iter().map(|row| row.get("key_id")).collect())
    }

    #[allow(dead_code)]
    async fn record_key_usage_mysql(&self, key_id: &str) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET last_used_at = NOW(), usage_count = usage_count + 1
            WHERE key_id = ?
            "#,
        )
        .bind(key_id)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to record key usage: {}", e))
        })?;

        Ok(())
    }

    #[allow(dead_code)]
    async fn record_audit_event_mysql(
        &self,
        key_id: &str,
        operation: KeyOperation,
        success: bool,
        error_message: Option<String>,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            INSERT INTO hammerwork_key_audit_log (
                key_id, operation, success, error_message, timestamp
            ) VALUES (?, ?, ?, ?, NOW())
            "#,
        )
        .bind(key_id)
        .bind(operation.to_string())
        .bind(success)
        .bind(error_message)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to record audit event: {}", e))
        })?;

        Ok(())
    }

    /// Check if a specific key is due for rotation
    #[cfg(feature = "mysql")]
    pub async fn is_key_due_for_rotation(&self, key_id: &str) -> Result<bool, EncryptionError> {
        let result = sqlx::query(
            r#"
            SELECT COUNT(*) as count
            FROM hammerwork_encryption_keys
            WHERE key_id = ?
            AND status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .bind(key_id)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to check rotation status for key {}: {}",
                key_id, e
            ))
        })?;

        let count: i64 = result.get("count");
        Ok(count > 0)
    }

    /// Update rotation schedule for a key (MySQL)
    async fn update_key_rotation_schedule_mysql(
        &self,
        key_id: &str,
        rotation_interval: Option<Duration>,
        next_rotation_at: Option<DateTime<Utc>>,
    ) -> Result<(), EncryptionError> {
        let interval_seconds = rotation_interval.map(|interval| interval.num_seconds());

        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET rotation_interval_seconds = ?, next_rotation_at = ?
            WHERE key_id = ? AND status = 'Active'
            "#,
        )
        .bind(interval_seconds)
        .bind(next_rotation_at)
        .bind(key_id)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to update rotation schedule for key {}: {}",
                key_id, e
            ))
        })?;

        info!(
            "Updated rotation schedule for key {}: interval={:?}, next_rotation={:?}",
            key_id, rotation_interval, next_rotation_at
        );
        Ok(())
    }

    /// Get rotation schedule for a key (MySQL)
    async fn get_key_rotation_schedule_mysql(
        &self,
        key_id: &str,
    ) -> Result<Option<DateTime<Utc>>, EncryptionError> {
        let result = sqlx::query(
            r#"
            SELECT next_rotation_at
            FROM hammerwork_encryption_keys
            WHERE key_id = ? AND status = 'Active'
            ORDER BY key_version DESC
            LIMIT 1
            "#,
        )
        .bind(key_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to get rotation schedule for key {}: {}",
                key_id, e
            ))
        })?;

        match result {
            Some(row) => Ok(row.get("next_rotation_at")),
            None => Ok(None),
        }
    }

    /// Schedule a key for rotation at a specific time (MySQL)
    async fn schedule_key_rotation_mysql(
        &self,
        key_id: &str,
        rotation_time: DateTime<Utc>,
    ) -> Result<(), EncryptionError> {
        sqlx::query(
            r#"
            UPDATE hammerwork_encryption_keys
            SET next_rotation_at = ?
            WHERE key_id = ? AND status = 'Active'
            "#,
        )
        .bind(rotation_time)
        .bind(key_id)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!(
                "Failed to schedule rotation for key {}: {}",
                key_id, e
            ))
        })?;

        info!("Scheduled rotation for key {} at {}", key_id, rotation_time);
        Ok(())
    }

    /// Get scheduled rotations within a time window (MySQL)
    async fn get_scheduled_rotations_mysql(
        &self,
        from_time: DateTime<Utc>,
        to_time: DateTime<Utc>,
    ) -> Result<Vec<(String, DateTime<Utc>)>, EncryptionError> {
        let rows = sqlx::query(
            r#"
            SELECT key_id, next_rotation_at
            FROM hammerwork_encryption_keys
            WHERE status = 'Active'
            AND next_rotation_at IS NOT NULL
            AND next_rotation_at BETWEEN ? AND ?
            ORDER BY next_rotation_at ASC
            "#,
        )
        .bind(from_time)
        .bind(to_time)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::KeyManagement(format!("Failed to get scheduled rotations: {}", e))
        })?;

        let scheduled_rotations = rows
            .into_iter()
            .filter_map(|row| {
                let key_id: String = row.get("key_id");
                let rotation_time: Option<DateTime<Utc>> = row.get("next_rotation_at");
                rotation_time.map(|time| (key_id, time))
            })
            .collect();

        Ok(scheduled_rotations)
    }

    /// Update the rotation schedule for a key (MySQL)
    pub async fn update_key_rotation_schedule(
        &self,
        key_id: &str,
        rotation_interval: Option<Duration>,
    ) -> Result<(), EncryptionError> {
        let next_rotation_at = rotation_interval.map(|interval| Utc::now() + interval);
        self.update_key_rotation_schedule_mysql(key_id, rotation_interval, next_rotation_at)
            .await
    }

    /// Get the next scheduled rotation time for a key (MySQL)
    pub async fn get_key_rotation_schedule(
        &self,
        key_id: &str,
    ) -> Result<Option<DateTime<Utc>>, EncryptionError> {
        self.get_key_rotation_schedule_mysql(key_id).await
    }

    /// Schedule a key for future rotation (MySQL)
    pub async fn schedule_key_rotation(
        &self,
        key_id: &str,
        rotation_time: DateTime<Utc>,
    ) -> Result<(), EncryptionError> {
        self.schedule_key_rotation_mysql(key_id, rotation_time)
            .await
    }

    /// Get all keys scheduled for rotation within a time window (MySQL)
    pub async fn get_scheduled_rotations(
        &self,
        from_time: DateTime<Utc>,
        to_time: DateTime<Utc>,
    ) -> Result<Vec<(String, DateTime<Utc>)>, EncryptionError> {
        self.get_scheduled_rotations_mysql(from_time, to_time).await
    }

    /// Query statistics from MySQL
    #[cfg(feature = "mysql")]
    pub async fn query_database_statistics(&self) -> Result<KeyManagerStats, EncryptionError> {
        // Execute multiple queries to gather comprehensive statistics
        let basic_counts = sqlx::query(
            r#"
            SELECT 
                COUNT(*) as total_keys,
                COUNT(CASE WHEN status = 'Active' THEN 1 END) as active_keys,
                COUNT(CASE WHEN status = 'Retired' THEN 1 END) as retired_keys,
                COUNT(CASE WHEN status = 'Revoked' THEN 1 END) as revoked_keys,
                COUNT(CASE WHEN status = 'Expired' THEN 1 END) as expired_keys
            FROM hammerwork_encryption_keys
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query key counts: {}", e))
        })?;

        let total_keys: i64 = basic_counts.get("total_keys");
        let active_keys: i64 = basic_counts.get("active_keys");
        let retired_keys: i64 = basic_counts.get("retired_keys");
        let revoked_keys: i64 = basic_counts.get("revoked_keys");
        let expired_keys: i64 = basic_counts.get("expired_keys");

        // Calculate average key age (MySQL syntax)
        let age_result = sqlx::query(
            r#"
            SELECT 
                COALESCE(AVG(TIMESTAMPDIFF(DAY, created_at, NOW())), 0) as avg_age_days
            FROM hammerwork_encryption_keys 
            WHERE status IN ('Active', 'Retired')
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query average age: {}", e))
        })?;

        let average_key_age_days: f64 = age_result.get("avg_age_days");

        // Count keys expiring soon (within 7 days)
        let expiring_result = sqlx::query(
            r#"
            SELECT COUNT(*) as expiring_soon
            FROM hammerwork_encryption_keys 
            WHERE status = 'Active' 
            AND expires_at IS NOT NULL 
            AND expires_at <= DATE_ADD(NOW(), INTERVAL 7 DAY)
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query expiring keys: {}", e))
        })?;

        let keys_expiring_soon: i64 = expiring_result.get("expiring_soon");

        // Count keys due for rotation
        let rotation_result = sqlx::query(
            r#"
            SELECT COUNT(*) as due_for_rotation
            FROM hammerwork_encryption_keys 
            WHERE status = 'Active' 
            AND next_rotation_at IS NOT NULL 
            AND next_rotation_at <= NOW()
            "#,
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| {
            EncryptionError::DatabaseError(format!("Failed to query rotation due keys: {}", e))
        })?;

        let keys_due_for_rotation: i64 = rotation_result.get("due_for_rotation");

        Ok(KeyManagerStats {
            total_keys: total_keys as u64,
            active_keys: active_keys as u64,
            retired_keys: retired_keys as u64,
            revoked_keys: revoked_keys as u64,
            expired_keys: expired_keys as u64,
            average_key_age_days,
            keys_expiring_soon: keys_expiring_soon as u64,
            keys_due_for_rotation: keys_due_for_rotation as u64,
            // Keep existing memory-tracked values
            total_access_operations: 0, // This should be tracked in memory or separate table
            rotations_performed: 0,     // This should be tracked in memory or separate table
        })
    }

    /// Get keys due for rotation
    #[cfg(feature = "mysql")]
    pub async fn get_keys_due_for_rotation(&self) -> Result<Vec<String>, EncryptionError> {
        self.get_keys_due_for_rotation_mysql().await
    }
}

impl Default for KeyManagerStats {
    fn default() -> Self {
        Self {
            total_keys: 0,
            active_keys: 0,
            retired_keys: 0,
            revoked_keys: 0,
            expired_keys: 0,
            total_access_operations: 0,
            rotations_performed: 0,
            average_key_age_days: 0.0,
            keys_expiring_soon: 0,
            keys_due_for_rotation: 0,
        }
    }
}

// Helper functions for parsing database values
pub fn parse_algorithm(s: &str) -> Result<EncryptionAlgorithm, EncryptionError> {
    match s {
        "AES256GCM" => Ok(EncryptionAlgorithm::AES256GCM),
        "ChaCha20Poly1305" => Ok(EncryptionAlgorithm::ChaCha20Poly1305),
        _ => Err(EncryptionError::KeyManagement(format!(
            "Unknown algorithm: {}",
            s
        ))),
    }
}

pub fn parse_key_source(s: &str) -> Result<KeySource, EncryptionError> {
    if s.starts_with("Environment(") && s.ends_with(")") {
        let env_var = s
            .strip_prefix("Environment(")
            .unwrap()
            .strip_suffix(")")
            .unwrap();
        Ok(KeySource::Environment(env_var.to_string()))
    } else if s.starts_with("Static(") && s.ends_with(")") {
        let static_key = s
            .strip_prefix("Static(")
            .unwrap()
            .strip_suffix(")")
            .unwrap();
        Ok(KeySource::Static(static_key.to_string()))
    } else if s.starts_with("Generated(") && s.ends_with(")") {
        let generated_type = s
            .strip_prefix("Generated(")
            .unwrap()
            .strip_suffix(")")
            .unwrap();
        Ok(KeySource::Generated(generated_type.to_string()))
    } else if s.starts_with("External(") && s.ends_with(")") {
        let external_id = s
            .strip_prefix("External(")
            .unwrap()
            .strip_suffix(")")
            .unwrap();
        Ok(KeySource::External(external_id.to_string()))
    } else {
        Err(EncryptionError::KeyManagement(format!(
            "Unknown key source: {}",
            s
        )))
    }
}

pub fn parse_key_purpose(s: &str) -> Result<KeyPurpose, EncryptionError> {
    match s {
        "Encryption" => Ok(KeyPurpose::Encryption),
        "MAC" => Ok(KeyPurpose::MAC),
        "KEK" => Ok(KeyPurpose::KEK),
        _ => Err(EncryptionError::KeyManagement(format!(
            "Unknown key purpose: {}",
            s
        ))),
    }
}

pub fn parse_key_status(s: &str) -> Result<KeyStatus, EncryptionError> {
    match s {
        "Active" => Ok(KeyStatus::Active),
        "Retired" => Ok(KeyStatus::Retired),
        "Revoked" => Ok(KeyStatus::Revoked),
        "Expired" => Ok(KeyStatus::Expired),
        _ => Err(EncryptionError::KeyManagement(format!(
            "Unknown key status: {}",
            s
        ))),
    }
}

#[cfg(feature = "postgres")]
#[allow(dead_code)]
fn parse_postgres_interval(interval_str: &str) -> Option<Duration> {
    // Parse PostgreSQL INTERVAL format like "3600 seconds"
    if let Some(seconds_str) = interval_str.strip_suffix(" seconds") {
        if let Ok(seconds) = seconds_str.parse::<i64>() {
            return Some(Duration::seconds(seconds));
        }
    }
    None
}

// Add Display implementations for enum serialization
impl std::fmt::Display for KeyPurpose {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyPurpose::Encryption => write!(f, "Encryption"),
            KeyPurpose::MAC => write!(f, "MAC"),
            KeyPurpose::KEK => write!(f, "KEK"),
        }
    }
}

impl std::fmt::Display for KeyStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyStatus::Active => write!(f, "Active"),
            KeyStatus::Retired => write!(f, "Retired"),
            KeyStatus::Revoked => write!(f, "Revoked"),
            KeyStatus::Expired => write!(f, "Expired"),
        }
    }
}

impl std::fmt::Display for EncryptionAlgorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EncryptionAlgorithm::AES256GCM => write!(f, "AES256GCM"),
            EncryptionAlgorithm::ChaCha20Poly1305 => write!(f, "ChaCha20Poly1305"),
        }
    }
}

impl std::fmt::Display for KeySource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeySource::Environment(env_var) => write!(f, "Environment({})", env_var),
            KeySource::Static(key) => write!(f, "Static({})", key),
            KeySource::Generated(gen_type) => write!(f, "Generated({})", gen_type),
            KeySource::External(ext_id) => write!(f, "External({})", ext_id),
        }
    }
}

impl std::fmt::Display for KeyOperation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyOperation::Create => write!(f, "Create"),
            KeyOperation::Access => write!(f, "Access"),
            KeyOperation::Rotate => write!(f, "Rotate"),
            KeyOperation::Retire => write!(f, "Retire"),
            KeyOperation::Revoke => write!(f, "Revoke"),
            KeyOperation::Delete => write!(f, "Delete"),
            KeyOperation::Update => write!(f, "Update"),
        }
    }
}

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

    #[tokio::test]
    async fn test_key_manager_config_creation() {
        let config = KeyManagerConfig::new()
            .with_master_key_env("TEST_MASTER_KEY")
            .with_auto_rotation_enabled(true)
            .with_rotation_interval(Duration::days(30))
            .with_audit_enabled(true);

        assert_eq!(
            config.master_key_source,
            KeySource::Environment("TEST_MASTER_KEY".to_string())
        );
        assert!(config.auto_rotation_enabled);
        assert_eq!(config.default_rotation_interval, Duration::days(30));
        assert!(config.audit_enabled);
    }

    #[test]
    fn test_key_purpose_serialization() {
        let purpose = KeyPurpose::Encryption;
        let serialized = serde_json::to_string(&purpose).unwrap();
        let deserialized: KeyPurpose = serde_json::from_str(&serialized).unwrap();
        assert_eq!(purpose, deserialized);
    }

    #[test]
    fn test_key_status_transitions() {
        let status = KeyStatus::Active;
        assert_eq!(status, KeyStatus::Active);

        let status = KeyStatus::Retired;
        assert_ne!(status, KeyStatus::Active);
    }

    #[test]
    fn test_external_kms_config() {
        let mut auth_config = HashMap::new();
        auth_config.insert("access_key_id".to_string(), "test_key".to_string());

        let kms_config = ExternalKmsConfig {
            service_type: "AWS".to_string(),
            endpoint: "https://kms.us-east-1.amazonaws.com".to_string(),
            auth_config,
            region: Some("us-east-1".to_string()),
            namespace: Some("hammerwork".to_string()),
        };

        assert_eq!(kms_config.service_type, "AWS");
        assert!(kms_config.auth_config.contains_key("access_key_id"));
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_master_key_storage_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default();
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Test generating a master key (which handles storage internally)
        let master_key_id = key_manager.generate_master_key().await.unwrap();

        // Test finding the stored key ID
        let found_id = key_manager.find_master_key_id_in_database().await.unwrap();
        assert!(found_id.is_some(), "Should find the stored master key ID");
        assert_eq!(
            found_id.unwrap(),
            master_key_id,
            "Found ID should match stored ID"
        );
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_master_key_storage_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default();
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Test generating a master key (which handles storage internally)
        let master_key_id = key_manager.generate_master_key().await.unwrap();

        // Test finding the stored key ID
        let found_id = key_manager.find_master_key_id_in_database().await.unwrap();
        assert!(found_id.is_some(), "Should find the stored master key ID");
        assert_eq!(
            found_id.unwrap(),
            master_key_id,
            "Found ID should match stored ID"
        );
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn test_system_key_derivation() {
        let config = KeyManagerConfig::default();
        // Create a minimal struct just for testing the derivation logic
        let key_manager = TestKeyManager { config };

        let salt = [1u8; 32];
        let result = key_manager.derive_system_encryption_key(&salt);

        assert!(result.is_ok());
        let derived_key = result.unwrap();
        assert_eq!(derived_key.len(), 32); // Should be 32 bytes for AES-256

        // Test deterministic nature - same salt should produce same key
        let result2 = key_manager.derive_system_encryption_key(&salt);
        assert!(result2.is_ok());
        assert_eq!(derived_key, result2.unwrap());
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn test_system_key_encryption_decryption() {
        let config = KeyManagerConfig::default();
        let key_manager = TestKeyManager { config };

        let system_key = [0u8; 32]; // Test key
        let plaintext = b"test master key material";

        let result = key_manager.encrypt_with_system_key(&system_key, plaintext);
        assert!(result.is_ok());

        let encrypted = result.unwrap();
        assert!(encrypted.len() > plaintext.len()); // Should be larger due to nonce + auth tag
        assert_ne!(&encrypted[12..], plaintext); // Encrypted data should be different
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_get_or_create_master_key_id_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        let key_material = b"test_key_material_for_id_generation";

        // First call should create a new ID
        let id1 = key_manager
            .get_or_create_master_key_id(key_material)
            .await
            .unwrap();

        // Second call with same material should return the same ID
        let id2 = key_manager
            .get_or_create_master_key_id(key_material)
            .await
            .unwrap();
        assert_eq!(id1, id2, "Should return the same ID for same key material");

        // Different material should produce different ID
        let different_material = b"different_test_key_material_here";
        let id3 = key_manager
            .get_or_create_master_key_id(different_material)
            .await
            .unwrap();
        assert_ne!(
            id1, id3,
            "Different key material should produce different ID"
        );
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_get_or_create_master_key_id_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        let key_material = b"test_key_material_for_id_generation";

        // First call should create a new ID
        let id1 = key_manager
            .get_or_create_master_key_id(key_material)
            .await
            .unwrap();

        // Second call with same material should return the same ID
        let id2 = key_manager
            .get_or_create_master_key_id(key_material)
            .await
            .unwrap();
        assert_eq!(id1, id2, "Should return the same ID for same key material");

        // Different material should produce different ID
        let different_material = b"different_test_key_material_here";
        let id3 = key_manager
            .get_or_create_master_key_id(different_material)
            .await
            .unwrap();
        assert_ne!(
            id1, id3,
            "Different key material should produce different ID"
        );
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn test_master_key_id_generation() {
        let key_material = b"test key material for ID generation";

        // Test deterministic ID generation
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(key_material);
        hasher.update(b"hammerwork-master-key-v1");
        let hash = hasher.finalize();

        let expected_id = Uuid::from_bytes([
            hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7], hash[8],
            hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15],
        ]);

        // Same material should produce same ID
        let mut hasher2 = Sha256::new();
        hasher2.update(key_material);
        hasher2.update(b"hammerwork-master-key-v1");
        let hash2 = hasher2.finalize();

        let id2 = Uuid::from_bytes([
            hash2[0], hash2[1], hash2[2], hash2[3], hash2[4], hash2[5], hash2[6], hash2[7],
            hash2[8], hash2[9], hash2[10], hash2[11], hash2[12], hash2[13], hash2[14], hash2[15],
        ]);

        assert_eq!(expected_id, id2);
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_key_rotation_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default().with_auto_rotation_enabled(true);
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Generate a test key with rotation schedule
        let key_id = key_manager
            .generate_key_with_options(
                "rotation-test-key",
                EncryptionAlgorithm::AES256GCM,
                KeyPurpose::Encryption,
                None,                     // expires_at
                Some(Duration::days(30)), // 30-day rotation interval
            )
            .await
            .unwrap();

        // Verify initial key version
        let initial_key = key_manager.load_key_postgres(&key_id).await.unwrap();
        assert_eq!(initial_key.version, 1);
        assert!(initial_key.next_rotation_at.is_some());

        // Perform manual rotation
        let new_version = key_manager.rotate_key(&key_id).await.unwrap();
        assert_eq!(new_version, 2);

        // Verify rotation worked
        let rotated_key = key_manager.load_key_postgres(&key_id).await.unwrap();
        assert_eq!(rotated_key.version, 2);
        assert_eq!(rotated_key.status, KeyStatus::Active);
        assert!(rotated_key.rotated_at.is_some());
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_key_rotation_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default().with_auto_rotation_enabled(true);
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Generate a test key with rotation schedule
        let key_id = key_manager
            .generate_key_with_options(
                "rotation-test-key",
                EncryptionAlgorithm::AES256GCM,
                KeyPurpose::Encryption,
                None,                     // expires_at
                Some(Duration::days(30)), // 30-day rotation interval
            )
            .await
            .unwrap();

        // Verify initial key version
        let initial_key = key_manager.load_key_mysql(&key_id).await.unwrap();
        assert_eq!(initial_key.version, 1);
        assert!(initial_key.next_rotation_at.is_some());

        // Perform manual rotation
        let new_version = key_manager.rotate_key(&key_id).await.unwrap();
        assert_eq!(new_version, 2);

        // Verify rotation worked
        let rotated_key = key_manager.load_key_mysql(&key_id).await.unwrap();
        assert_eq!(rotated_key.version, 2);
        assert_eq!(rotated_key.status, KeyStatus::Active);
        assert!(rotated_key.rotated_at.is_some());
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_rotation_scheduling_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create a test key first
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "schedule-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now(),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(90)),
            next_rotation_at: None, // Initially no rotation scheduled
            key_strength: 256,
            master_key_id: None,
            last_used_at: None,
            usage_count: 0,
        };

        key_manager.store_key_postgres(&test_key).await.unwrap();

        // Schedule rotation for 1 hour from now
        let rotation_time = Utc::now() + Duration::hours(1);
        key_manager
            .schedule_key_rotation("schedule-test-key", rotation_time)
            .await
            .unwrap();

        // Verify the schedule was set
        let schedule = key_manager
            .get_key_rotation_schedule("schedule-test-key")
            .await
            .unwrap();
        assert!(schedule.is_some());
        let scheduled_time = schedule.unwrap();

        // Allow for small time differences due to test execution time
        let time_diff = (scheduled_time - rotation_time).num_seconds().abs();
        assert!(
            time_diff < 5,
            "Scheduled time should be close to requested time"
        );

        // Test querying scheduled rotations
        let from_time = Utc::now();
        let to_time = Utc::now() + Duration::hours(2);
        let scheduled_rotations = key_manager
            .get_scheduled_rotations(from_time, to_time)
            .await
            .unwrap();

        assert_eq!(scheduled_rotations.len(), 1);
        assert_eq!(scheduled_rotations[0].0, "schedule-test-key");
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_rotation_scheduling_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create a test key first
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "schedule-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now(),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(90)),
            next_rotation_at: None, // Initially no rotation scheduled
            key_strength: 256,
            master_key_id: None,
            last_used_at: None,
            usage_count: 0,
        };

        key_manager.store_key_mysql(&test_key).await.unwrap();

        // Schedule rotation for 1 hour from now
        let rotation_time = Utc::now() + Duration::hours(1);
        key_manager
            .schedule_key_rotation("schedule-test-key", rotation_time)
            .await
            .unwrap();

        // Verify the schedule was set
        let schedule = key_manager
            .get_key_rotation_schedule("schedule-test-key")
            .await
            .unwrap();
        assert!(schedule.is_some());
        let scheduled_time = schedule.unwrap();

        // Allow for small time differences due to test execution time
        let time_diff = (scheduled_time - rotation_time).num_seconds().abs();
        assert!(
            time_diff < 5,
            "Scheduled time should be close to requested time"
        );

        // Test querying scheduled rotations
        let from_time = Utc::now();
        let to_time = Utc::now() + Duration::hours(2);
        let scheduled_rotations = key_manager
            .get_scheduled_rotations(from_time, to_time)
            .await
            .unwrap();

        assert_eq!(scheduled_rotations.len(), 1);
        assert_eq!(scheduled_rotations[0].0, "schedule-test-key");
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_automatic_rotation_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default().with_auto_rotation_enabled(true);
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create a key that is due for rotation (next_rotation_at in the past)
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "auto-rotation-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(90),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(30)),
            next_rotation_at: Some(Utc::now() - Duration::hours(1)), // Due for rotation
            key_strength: 256,
            master_key_id: None,
            last_used_at: None,
            usage_count: 0,
        };

        key_manager.store_key_postgres(&test_key).await.unwrap();

        // Verify key is due for rotation
        let is_due = key_manager
            .is_key_due_for_rotation("auto-rotation-test-key")
            .await
            .unwrap();
        assert!(is_due, "Key should be due for rotation");

        // Perform automatic rotation
        let rotated_keys = key_manager.perform_automatic_rotation().await.unwrap();
        assert_eq!(rotated_keys.len(), 1);
        assert_eq!(rotated_keys[0], "auto-rotation-test-key");

        // Verify the key was rotated
        let rotated_key = key_manager
            .load_key_postgres("auto-rotation-test-key")
            .await
            .unwrap();
        assert_eq!(rotated_key.version, 2);
        assert!(rotated_key.rotated_at.is_some());
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_automatic_rotation_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default().with_auto_rotation_enabled(true);
        let mut key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create a key that is due for rotation (next_rotation_at in the past)
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "auto-rotation-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(90),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(30)),
            next_rotation_at: Some(Utc::now() - Duration::hours(1)), // Due for rotation
            key_strength: 256,
            master_key_id: None,
            last_used_at: None,
            usage_count: 0,
        };

        key_manager.store_key_mysql(&test_key).await.unwrap();

        // Verify key is due for rotation
        let is_due = key_manager
            .is_key_due_for_rotation("auto-rotation-test-key")
            .await
            .unwrap();
        assert!(is_due, "Key should be due for rotation");

        // Perform automatic rotation
        let rotated_keys = key_manager.perform_automatic_rotation().await.unwrap();
        assert_eq!(rotated_keys.len(), 1);
        assert_eq!(rotated_keys[0], "auto-rotation-test-key");

        // Verify the key was rotated
        let rotated_key = key_manager
            .load_key_mysql("auto-rotation-test-key")
            .await
            .unwrap();
        assert_eq!(rotated_key.version, 2);
        assert!(rotated_key.rotated_at.is_some());
    }

    // Test-only struct for unit testing crypto functions without database
    #[cfg(feature = "encryption")]
    struct TestKeyManager {
        config: KeyManagerConfig,
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_database_statistics_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create test keys with different statuses
        let active_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-active-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(10),
            created_by: Some("test".to_string()),
            expires_at: Some(Utc::now() + Duration::days(30)),
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(90)),
            next_rotation_at: Some(Utc::now() + Duration::days(5)), // Due for rotation soon
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::hours(1)),
            usage_count: 5,
        };

        let retired_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-retired-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(20),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: Some(Utc::now() - Duration::days(5)),
            retired_at: Some(Utc::now() - Duration::days(5)),
            status: KeyStatus::Retired,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::days(6)),
            usage_count: 10,
        };

        let expiring_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-expiring-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(5),
            created_by: Some("test".to_string()),
            expires_at: Some(Utc::now() + Duration::days(3)), // Expires soon
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::hours(2)),
            usage_count: 2,
        };

        // Store test keys
        key_manager.store_key_postgres(&active_key).await.unwrap();
        key_manager.store_key_postgres(&retired_key).await.unwrap();
        key_manager.store_key_postgres(&expiring_key).await.unwrap();

        // Query and verify statistics
        let stats = key_manager.query_database_statistics().await.unwrap();

        assert_eq!(stats.total_keys, 3, "Should have 3 total keys");
        assert_eq!(stats.active_keys, 2, "Should have 2 active keys");
        assert_eq!(stats.retired_keys, 1, "Should have 1 retired key");
        assert_eq!(stats.revoked_keys, 0, "Should have 0 revoked keys");
        assert_eq!(stats.expired_keys, 0, "Should have 0 expired keys");

        // Average age should be between 5 and 20 days (approximate check)
        assert!(
            stats.average_key_age_days > 5.0 && stats.average_key_age_days < 20.0,
            "Average key age should be reasonable: {}",
            stats.average_key_age_days
        );

        assert_eq!(
            stats.keys_expiring_soon, 1,
            "Should have 1 key expiring soon"
        );
        assert_eq!(
            stats.keys_due_for_rotation, 1,
            "Should have 1 key due for rotation"
        );
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_database_statistics_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Create test keys with different statuses (same as PostgreSQL test)
        let active_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-active-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(10),
            created_by: Some("test".to_string()),
            expires_at: Some(Utc::now() + Duration::days(30)),
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: Some(Duration::days(90)),
            next_rotation_at: Some(Utc::now() + Duration::days(5)), // Due for rotation soon
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::hours(1)),
            usage_count: 5,
        };

        let retired_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-retired-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(20),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: Some(Utc::now() - Duration::days(5)),
            retired_at: Some(Utc::now() - Duration::days(5)),
            status: KeyStatus::Retired,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::days(6)),
            usage_count: 10,
        };

        let expiring_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "test-expiring-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(5),
            created_by: Some("test".to_string()),
            expires_at: Some(Utc::now() + Duration::days(3)), // Expires soon
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now() - Duration::hours(2)),
            usage_count: 2,
        };

        // Store test keys
        key_manager.store_key_mysql(&active_key).await.unwrap();
        key_manager.store_key_mysql(&retired_key).await.unwrap();
        key_manager.store_key_mysql(&expiring_key).await.unwrap();

        // Query and verify statistics
        let stats = key_manager.query_database_statistics().await.unwrap();

        assert_eq!(stats.total_keys, 3, "Should have 3 total keys");
        assert_eq!(stats.active_keys, 2, "Should have 2 active keys");
        assert_eq!(stats.retired_keys, 1, "Should have 1 retired key");
        assert_eq!(stats.revoked_keys, 0, "Should have 0 revoked keys");
        assert_eq!(stats.expired_keys, 0, "Should have 0 expired keys");

        // Average age should be between 5 and 20 days (approximate check)
        assert!(
            stats.average_key_age_days > 5.0 && stats.average_key_age_days < 20.0,
            "Average key age should be reasonable: {}",
            stats.average_key_age_days
        );

        assert_eq!(
            stats.keys_expiring_soon, 1,
            "Should have 1 key expiring soon"
        );
        assert_eq!(
            stats.keys_due_for_rotation, 1,
            "Should have 1 key due for rotation"
        );
    }

    #[cfg(all(feature = "encryption", feature = "postgres"))]
    #[sqlx::test]
    async fn test_refresh_stats_integration_postgres(pool: sqlx::PgPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Initially stats should be mostly zeros
        let initial_stats = key_manager.get_stats().await;
        assert_eq!(initial_stats.total_keys, 0);

        // Add a test key
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "refresh-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(7),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now()),
            usage_count: 1,
        };

        key_manager.store_key_postgres(&test_key).await.unwrap();

        // Refresh stats and verify they're updated
        key_manager.refresh_stats().await.unwrap();
        let updated_stats = key_manager.get_stats().await;

        assert_eq!(
            updated_stats.total_keys, 1,
            "Stats should reflect the added key"
        );
        assert_eq!(updated_stats.active_keys, 1, "Should have 1 active key");
        assert!(
            updated_stats.average_key_age_days > 6.0 && updated_stats.average_key_age_days < 8.0,
            "Average age should be around 7 days: {}",
            updated_stats.average_key_age_days
        );
    }

    #[cfg(all(feature = "encryption", feature = "mysql"))]
    #[sqlx::test]
    async fn test_refresh_stats_integration_mysql(pool: sqlx::MySqlPool) {
        let config = KeyManagerConfig::default();
        let key_manager = KeyManager::new(config, pool).await.unwrap();

        // Initially stats should be mostly zeros
        let initial_stats = key_manager.get_stats().await;
        assert_eq!(initial_stats.total_keys, 0);

        // Add a test key
        let test_key = EncryptionKey {
            id: Uuid::new_v4(),
            key_id: "refresh-test-key".to_string(),
            version: 1,
            algorithm: EncryptionAlgorithm::AES256GCM,
            encrypted_key_material: vec![1, 2, 3, 4],
            derivation_salt: Some(vec![5, 6, 7, 8]),
            source: KeySource::Generated("test_key".to_string()),
            purpose: KeyPurpose::Encryption,
            created_at: Utc::now() - Duration::days(7),
            created_by: Some("test".to_string()),
            expires_at: None,
            rotated_at: None,
            retired_at: None,
            status: KeyStatus::Active,
            rotation_interval: None,
            next_rotation_at: None,
            key_strength: 256,
            master_key_id: None,
            last_used_at: Some(Utc::now()),
            usage_count: 1,
        };

        key_manager.store_key_mysql(&test_key).await.unwrap();

        // Refresh stats and verify they're updated
        key_manager.refresh_stats().await.unwrap();
        let updated_stats = key_manager.get_stats().await;

        assert_eq!(
            updated_stats.total_keys, 1,
            "Stats should reflect the added key"
        );
        assert_eq!(updated_stats.active_keys, 1, "Should have 1 active key");
        assert!(
            updated_stats.average_key_age_days > 6.0 && updated_stats.average_key_age_days < 8.0,
            "Average age should be around 7 days: {}",
            updated_stats.average_key_age_days
        );
    }

    #[cfg(feature = "encryption")]
    impl TestKeyManager {
        #[allow(dead_code)]
        fn derive_system_encryption_key(&self, salt: &[u8]) -> Result<Vec<u8>, EncryptionError> {
            use argon2::{
                Argon2,
                password_hash::{PasswordHasher, SaltString},
            };

            // Use a combination of system properties and configuration for key derivation
            let mut input = Vec::new();
            input.extend_from_slice(b"hammerwork-system-key-v1");

            // Add configuration-based entropy
            if let Some(ref external_config) = self.config.external_kms_config {
                input.extend_from_slice(external_config.service_type.as_bytes());
                input.extend_from_slice(external_config.endpoint.as_bytes());
                if let Some(ref region) = external_config.region {
                    input.extend_from_slice(region.as_bytes());
                }
            }

            // Add system-specific entropy (hostname, etc.)
            if let Ok(hostname) = std::env::var("HOSTNAME") {
                input.extend_from_slice(hostname.as_bytes());
            }

            // Use Argon2 for secure key derivation
            let argon2 = Argon2::default();
            let salt_string = SaltString::encode_b64(salt).map_err(|e| {
                EncryptionError::KeyManagement(format!("Failed to encode salt: {}", e))
            })?;

            let password_hash = argon2.hash_password(&input, &salt_string).map_err(|e| {
                EncryptionError::KeyManagement(format!("Key derivation failed: {}", e))
            })?;

            // Extract the raw hash bytes
            let hash = password_hash.hash.ok_or_else(|| {
                EncryptionError::KeyManagement("No hash in password result".to_string())
            })?;
            let hash_bytes = hash.as_bytes();

            // Return first 32 bytes for AES-256
            Ok(hash_bytes[0..32].to_vec())
        }

        #[allow(dead_code)]
        fn encrypt_with_system_key(
            &self,
            system_key: &[u8],
            plaintext: &[u8],
        ) -> Result<Vec<u8>, EncryptionError> {
            use aes_gcm::{
                Aes256Gcm, Nonce,
                aead::{Aead, KeyInit},
            };

            let cipher = Aes256Gcm::new_from_slice(system_key).map_err(|e| {
                EncryptionError::KeyManagement(format!("Failed to create cipher: {}", e))
            })?;

            // Generate random nonce
            let mut nonce_bytes = [0u8; 12];
            use rand::RngCore;
            rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
            let nonce = Nonce::from_slice(&nonce_bytes);

            // Encrypt the data
            let ciphertext = cipher
                .encrypt(nonce, plaintext)
                .map_err(|e| EncryptionError::KeyManagement(format!("Encryption failed: {}", e)))?;

            // Prepend nonce to ciphertext for storage
            let mut result = nonce_bytes.to_vec();
            result.extend_from_slice(&ciphertext);

            Ok(result)
        }
    }
}