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
//! Job types and utilities for representing work units in the job queue.
//!
//! This module provides the core [`Job`] struct and [`JobStatus`] enum that represent
//! individual units of work to be processed by workers. Jobs contain all the metadata
//! needed for scheduling, prioritization, retry logic, and lifecycle management.

use crate::cron::CronSchedule;
use crate::priority::JobPriority;
use crate::retry::RetryStrategy;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[cfg(any(feature = "postgres", feature = "mysql"))]
use sqlx::{Decode, Encode, Type};

#[cfg(feature = "postgres")]
use sqlx::Postgres;

#[cfg(feature = "mysql")]
use sqlx::MySql;

/// Unique identifier for a job.
///
/// Each job gets a unique UUID when created to enable tracking and management
/// throughout its lifecycle.
pub type JobId = Uuid;

/// The current status of a job in its lifecycle.
///
/// Jobs progress through various states from creation to completion or failure.
/// This enum tracks the current state to enable proper job management and statistics.
///
/// # Examples
///
/// ```rust
/// use hammerwork::JobStatus;
///
/// // Check if a job is in a final state
/// let status = JobStatus::Completed;
/// let is_final = matches!(status, JobStatus::Completed | JobStatus::Dead | JobStatus::TimedOut | JobStatus::Archived);
/// assert!(is_final);
/// ```
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum JobStatus {
    /// Job is waiting to be processed by a worker.
    Pending,
    /// Job is currently being processed by a worker.
    Running,
    /// Job completed successfully.
    Completed,
    /// Job failed but may be retried if it hasn't exhausted retry attempts.
    Failed,
    /// Job failed permanently after exhausting all retry attempts.
    Dead,
    /// Job was terminated due to exceeding its timeout duration.
    TimedOut,
    /// Job failed but is scheduled for retry.
    Retrying,
    /// Job has been archived for long-term storage.
    Archived,
}

impl JobStatus {
    /// Returns the string representation of the job status.
    pub fn as_str(&self) -> &'static str {
        match self {
            JobStatus::Pending => "Pending",
            JobStatus::Running => "Running",
            JobStatus::Completed => "Completed",
            JobStatus::Failed => "Failed",
            JobStatus::Dead => "Dead",
            JobStatus::TimedOut => "TimedOut",
            JobStatus::Retrying => "Retrying",
            JobStatus::Archived => "Archived",
        }
    }
}

// SQLx implementations for JobStatus to handle database encoding/decoding

#[cfg(feature = "postgres")]
impl Type<Postgres> for JobStatus {
    fn type_info() -> sqlx::postgres::PgTypeInfo {
        <String as Type<Postgres>>::type_info()
    }
}

#[cfg(feature = "postgres")]
impl Encode<'_, Postgres> for JobStatus {
    fn encode_by_ref(
        &self,
        buf: &mut sqlx::postgres::PgArgumentBuffer,
    ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> {
        let status_str = match self {
            JobStatus::Pending => "Pending",
            JobStatus::Running => "Running",
            JobStatus::Completed => "Completed",
            JobStatus::Failed => "Failed",
            JobStatus::Dead => "Dead",
            JobStatus::TimedOut => "TimedOut",
            JobStatus::Retrying => "Retrying",
            JobStatus::Archived => "Archived",
        };
        <&str as Encode<'_, Postgres>>::encode_by_ref(&status_str, buf)
    }
}

#[cfg(feature = "postgres")]
impl Decode<'_, Postgres> for JobStatus {
    fn decode(value: sqlx::postgres::PgValueRef<'_>) -> Result<Self, sqlx::error::BoxDynError> {
        let status_str = <String as Decode<Postgres>>::decode(value)?;
        // Handle both quoted (old format) and unquoted (new format) status values
        let cleaned_str = status_str.trim_matches('"');
        match cleaned_str {
            "Pending" => Ok(JobStatus::Pending),
            "Running" => Ok(JobStatus::Running),
            "Completed" => Ok(JobStatus::Completed),
            "Failed" => Ok(JobStatus::Failed),
            "Dead" => Ok(JobStatus::Dead),
            "TimedOut" => Ok(JobStatus::TimedOut),
            "Retrying" => Ok(JobStatus::Retrying),
            "Archived" => Ok(JobStatus::Archived),
            _ => Err(format!("Unknown job status: {}", status_str).into()),
        }
    }
}

#[cfg(feature = "mysql")]
impl Type<MySql> for JobStatus {
    fn type_info() -> sqlx::mysql::MySqlTypeInfo {
        <String as Type<MySql>>::type_info()
    }
}

#[cfg(feature = "mysql")]
impl Encode<'_, MySql> for JobStatus {
    fn encode_by_ref(
        &self,
        buf: &mut Vec<u8>,
    ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> {
        let status_str = match self {
            JobStatus::Pending => "Pending",
            JobStatus::Running => "Running",
            JobStatus::Completed => "Completed",
            JobStatus::Failed => "Failed",
            JobStatus::Dead => "Dead",
            JobStatus::TimedOut => "TimedOut",
            JobStatus::Retrying => "Retrying",
            JobStatus::Archived => "Archived",
        };
        <&str as Encode<'_, MySql>>::encode_by_ref(&status_str, buf)
    }
}

#[cfg(feature = "mysql")]
impl Decode<'_, MySql> for JobStatus {
    fn decode(value: sqlx::mysql::MySqlValueRef<'_>) -> Result<Self, sqlx::error::BoxDynError> {
        let status_str = <String as Decode<MySql>>::decode(value)?;
        // Handle both quoted (old format) and unquoted (new format) status values
        let cleaned_str = status_str.trim_matches('"');
        match cleaned_str {
            "Pending" => Ok(JobStatus::Pending),
            "Running" => Ok(JobStatus::Running),
            "Completed" => Ok(JobStatus::Completed),
            "Failed" => Ok(JobStatus::Failed),
            "Dead" => Ok(JobStatus::Dead),
            "TimedOut" => Ok(JobStatus::TimedOut),
            "Retrying" => Ok(JobStatus::Retrying),
            "Archived" => Ok(JobStatus::Archived),
            _ => Err(format!("Unknown job status: {}", status_str).into()),
        }
    }
}

/// Configuration for job result storage.
///
/// This enum determines where and how job results are stored when jobs complete successfully.
/// Different storage backends offer different trade-offs between performance, persistence,
/// and resource usage.
///
/// # Examples
///
/// ```rust
/// use hammerwork::job::ResultStorage;
///
/// // Store results in the database
/// let db_storage = ResultStorage::Database;
///
/// // Store results in memory (faster but not persistent)
/// let memory_storage = ResultStorage::Memory;
///
/// // Don't store results (default behavior)
/// let no_storage = ResultStorage::None;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ResultStorage {
    /// Store results in the database (persistent across restarts).
    Database,
    /// Store results in memory (faster access but lost on restart).
    Memory,
    /// Don't store job results (default behavior).
    None,
}

impl Default for ResultStorage {
    fn default() -> Self {
        Self::None
    }
}

/// Configuration for job result storage and management.
///
/// This struct contains settings that control how job results are stored,
/// how long they're retained, and when they should be cleaned up.
///
/// # Examples
///
/// ```rust
/// use hammerwork::job::{ResultConfig, ResultStorage};
/// use std::time::Duration;
///
/// // Store results in database for 7 days
/// let config = ResultConfig::new(ResultStorage::Database)
///     .with_ttl(Duration::from_secs(7 * 24 * 60 * 60));
///
/// // Store results in memory for 1 hour
/// let config = ResultConfig::new(ResultStorage::Memory)
///     .with_ttl(Duration::from_secs(3600));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultConfig {
    /// Where to store the job results.
    pub storage: ResultStorage,
    /// How long to keep results before expiring them.
    pub ttl: Option<std::time::Duration>,
    /// Maximum size of result data in bytes (for validation).
    pub max_size_bytes: Option<usize>,
}

impl ResultConfig {
    /// Creates a new result configuration with the specified storage backend.
    ///
    /// # Arguments
    ///
    /// * `storage` - The storage backend to use for results
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::job::{ResultConfig, ResultStorage};
    ///
    /// let config = ResultConfig::new(ResultStorage::Database);
    /// assert_eq!(config.storage, ResultStorage::Database);
    /// assert!(config.ttl.is_none());
    /// ```
    pub fn new(storage: ResultStorage) -> Self {
        Self {
            storage,
            ttl: None,
            max_size_bytes: None,
        }
    }

    /// Sets the time-to-live (TTL) for stored results.
    ///
    /// After this duration elapses, the result will be eligible for cleanup.
    ///
    /// # Arguments
    ///
    /// * `ttl` - How long to keep results before they expire
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::job::{ResultConfig, ResultStorage};
    /// use std::time::Duration;
    ///
    /// let config = ResultConfig::new(ResultStorage::Database)
    ///     .with_ttl(Duration::from_secs(3600)); // 1 hour
    /// ```
    pub fn with_ttl(mut self, ttl: std::time::Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Sets the maximum size for result data.
    ///
    /// This is used to validate result data before storage to prevent
    /// extremely large results from impacting system performance.
    ///
    /// # Arguments
    ///
    /// * `max_bytes` - Maximum allowed size for result data
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::job::{ResultConfig, ResultStorage};
    ///
    /// let config = ResultConfig::new(ResultStorage::Database)
    ///     .with_max_size(1024 * 1024); // 1MB limit
    /// ```
    pub fn with_max_size(mut self, max_bytes: usize) -> Self {
        self.max_size_bytes = Some(max_bytes);
        self
    }
}

impl Default for ResultConfig {
    fn default() -> Self {
        Self::new(ResultStorage::None)
    }
}

/// A unit of work to be processed by the job queue.
///
/// Jobs are the fundamental building blocks of the Hammerwork system. Each job contains:
/// - A unique identifier for tracking
/// - Queue name for routing to appropriate workers
/// - JSON payload containing the work data
/// - Scheduling and retry configuration
/// - Priority level for queue ordering
/// - Optional cron schedule for recurring jobs
/// - Timeout configuration for automatic termination
///
/// # Examples
///
/// ## Basic Job Creation
///
/// ```rust
/// use hammerwork::Job;
/// use serde_json::json;
///
/// let job = Job::new("email_queue".to_string(), json!({
///     "to": "user@example.com",
///     "subject": "Welcome!",
///     "body": "Thanks for signing up"
/// }));
///
/// assert_eq!(job.queue_name, "email_queue");
/// assert_eq!(job.max_attempts, 3); // Default retry attempts
/// ```
///
/// ## Job with Priority and Timeout
///
/// ```rust
/// use hammerwork::{Job, JobPriority};
/// use serde_json::json;
/// use std::time::Duration;
///
/// let job = Job::new("processing".to_string(), json!({"data": "important"}))
///     .as_high_priority()
///     .with_timeout(Duration::from_secs(300))
///     .with_max_attempts(5);
///
/// assert_eq!(job.priority, JobPriority::High);
/// assert_eq!(job.timeout, Some(Duration::from_secs(300)));
/// assert_eq!(job.max_attempts, 5);
/// ```
///
/// ## Delayed Job
///
/// ```rust
/// use hammerwork::Job;
/// use serde_json::json;
/// use chrono::Duration;
///
/// let job = Job::with_delay(
///     "notifications".to_string(),
///     json!({"message": "Reminder"}),
///     Duration::hours(1)
/// );
///
/// // Job will be scheduled to run 1 hour from now
/// assert!(job.scheduled_at > job.created_at);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
    /// Unique identifier for this job.
    pub id: JobId,
    /// Name of the queue this job belongs to.
    pub queue_name: String,
    /// JSON payload containing the work data.
    pub payload: serde_json::Value,
    /// Current status of the job.
    pub status: JobStatus,
    /// Number of times this job has been attempted.
    pub attempts: i32,
    /// Maximum number of attempts before marking the job as dead.
    pub max_attempts: i32,
    /// When the job was created.
    pub created_at: DateTime<Utc>,
    /// When the job should be processed (may be in the future for delayed jobs).
    pub scheduled_at: DateTime<Utc>,
    /// When the job started processing (if it has started).
    pub started_at: Option<DateTime<Utc>>,
    /// When the job completed successfully (if it completed).
    pub completed_at: Option<DateTime<Utc>>,
    /// When the job failed permanently (if it failed).
    pub failed_at: Option<DateTime<Utc>>,
    /// When the job timed out (if it timed out).
    pub timed_out_at: Option<DateTime<Utc>>,
    /// Maximum duration the job is allowed to run before timing out.
    pub timeout: Option<std::time::Duration>,
    /// Error message if the job failed.
    pub error_message: Option<String>,
    /// Priority level for queue ordering.
    pub priority: JobPriority,
    /// Cron expression for recurring jobs.
    pub cron_schedule: Option<String>,
    /// Next scheduled execution time for recurring jobs.
    pub next_run_at: Option<DateTime<Utc>>,
    /// Whether this is a recurring job.
    pub recurring: bool,
    /// Timezone for cron calculations.
    pub timezone: Option<String>,
    /// Batch ID if this job is part of a batch operation.
    pub batch_id: Option<crate::batch::BatchId>,
    /// Configuration for how job results should be stored.
    pub result_config: ResultConfig,
    /// The actual result data from job execution (if stored).
    pub result_data: Option<serde_json::Value>,
    /// When the result was stored (if applicable).
    pub result_stored_at: Option<DateTime<Utc>>,
    /// When the stored result will expire (if applicable).
    pub result_expires_at: Option<DateTime<Utc>>,
    /// Retry strategy for this job (overrides worker default if specified).
    pub retry_strategy: Option<RetryStrategy>,
    /// Job IDs this job depends on (must complete before this job can run).
    pub depends_on: Vec<JobId>,
    /// Job IDs that depend on this job (cached for performance).
    pub dependents: Vec<JobId>,
    /// Status of dependency resolution for this job.
    pub dependency_status: crate::workflow::DependencyStatus,
    /// ID of the workflow this job belongs to (if any).
    pub workflow_id: Option<crate::workflow::WorkflowId>,
    /// Name of the workflow this job belongs to (if any).
    pub workflow_name: Option<String>,
    /// Distributed trace identifier for cross-service tracing.
    pub trace_id: Option<String>,
    /// Business correlation identifier for grouping related operations.
    pub correlation_id: Option<String>,
    /// Parent span identifier for hierarchical tracing.
    pub parent_span_id: Option<String>,
    /// Serialized span context for trace propagation.
    pub span_context: Option<String>,
    /// Encryption configuration for this job's payload (if encrypted).
    #[cfg(feature = "encryption")]
    pub encryption_config: Option<crate::encryption::EncryptionConfig>,
    /// List of field names that contain PII and should be encrypted.
    pub pii_fields: Vec<String>,
    /// Retention policy for encrypted data (overrides default if specified).
    #[cfg(feature = "encryption")]
    pub retention_policy: Option<crate::encryption::RetentionPolicy>,
    /// Whether the payload is currently encrypted.
    pub is_encrypted: bool,
    /// Encrypted payload data (if job is encrypted).
    #[cfg(feature = "encryption")]
    pub encrypted_payload: Option<crate::encryption::EncryptedPayload>,
}

impl Job {
    /// Creates a new job with default settings.
    ///
    /// The job will be created with:
    /// - A unique UUID identifier
    /// - Normal priority level
    /// - 3 maximum retry attempts
    /// - Scheduled to run immediately
    /// - Pending status
    ///
    /// # Arguments
    ///
    /// * `queue_name` - The name of the queue this job should be processed by
    /// * `payload` - JSON data containing the work to be performed
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobStatus, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("email_queue".to_string(), json!({
    ///     "to": "user@example.com",
    ///     "subject": "Welcome!",
    ///     "template": "welcome"
    /// }));
    ///
    /// assert_eq!(job.queue_name, "email_queue");
    /// assert_eq!(job.status, JobStatus::Pending);
    /// assert_eq!(job.priority, JobPriority::Normal);
    /// assert_eq!(job.max_attempts, 3);
    /// assert_eq!(job.attempts, 0);
    /// assert!(!job.is_recurring());
    /// ```
    pub fn new(queue_name: String, payload: serde_json::Value) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            queue_name,
            payload,
            status: JobStatus::Pending,
            attempts: 0,
            max_attempts: 3,
            created_at: now,
            scheduled_at: now,
            started_at: None,
            completed_at: None,
            failed_at: None,
            timed_out_at: None,
            timeout: None,
            error_message: None,
            priority: JobPriority::default(),
            cron_schedule: None,
            next_run_at: None,
            recurring: false,
            timezone: None,
            batch_id: None,
            result_config: ResultConfig::default(),
            result_data: None,
            result_stored_at: None,
            result_expires_at: None,
            retry_strategy: None,
            depends_on: Vec::new(),
            dependents: Vec::new(),
            dependency_status: crate::workflow::DependencyStatus::None,
            workflow_id: None,
            workflow_name: None,
            trace_id: None,
            correlation_id: None,
            parent_span_id: None,
            span_context: None,
            #[cfg(feature = "encryption")]
            encryption_config: None,
            pii_fields: Vec::new(),
            #[cfg(feature = "encryption")]
            retention_policy: None,
            is_encrypted: false,
            #[cfg(feature = "encryption")]
            encrypted_payload: None,
        }
    }

    /// Creates a new job scheduled to run after a delay.
    ///
    /// This is useful for implementing delayed notifications, retries with backoff,
    /// or any work that should be performed at a specific time in the future.
    ///
    /// # Arguments
    ///
    /// * `queue_name` - The name of the queue this job should be processed by
    /// * `payload` - JSON data containing the work to be performed
    /// * `delay` - How long to wait before the job becomes eligible for processing
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use chrono::Duration;
    ///
    /// // Send a reminder email in 24 hours
    /// let job = Job::with_delay(
    ///     "email_queue".to_string(),
    ///     json!({
    ///         "to": "user@example.com",
    ///         "subject": "Don't forget to complete your profile",
    ///         "template": "reminder"
    ///     }),
    ///     Duration::hours(24)
    /// );
    ///
    /// // Job will be scheduled 24 hours from now
    /// assert!(job.scheduled_at > job.created_at);
    /// let delay_diff = job.scheduled_at - job.created_at;
    /// assert_eq!(delay_diff, Duration::hours(24));
    /// ```
    pub fn with_delay(
        queue_name: String,
        payload: serde_json::Value,
        delay: chrono::Duration,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            queue_name,
            payload,
            status: JobStatus::Pending,
            attempts: 0,
            max_attempts: 3,
            created_at: now,
            scheduled_at: now + delay,
            started_at: None,
            completed_at: None,
            failed_at: None,
            timed_out_at: None,
            timeout: None,
            error_message: None,
            priority: JobPriority::default(),
            cron_schedule: None,
            next_run_at: None,
            recurring: false,
            timezone: None,
            batch_id: None,
            result_config: ResultConfig::default(),
            result_data: None,
            result_stored_at: None,
            result_expires_at: None,
            retry_strategy: None,
            depends_on: Vec::new(),
            dependents: Vec::new(),
            dependency_status: crate::workflow::DependencyStatus::None,
            workflow_id: None,
            workflow_name: None,
            trace_id: None,
            correlation_id: None,
            parent_span_id: None,
            span_context: None,
            #[cfg(feature = "encryption")]
            encryption_config: None,
            pii_fields: Vec::new(),
            #[cfg(feature = "encryption")]
            retention_policy: None,
            is_encrypted: false,
            #[cfg(feature = "encryption")]
            encrypted_payload: None,
        }
    }

    /// Sets the maximum number of retry attempts for this job.
    ///
    /// When a job fails, it will be retried up to this many times before being
    /// marked as dead. The default is 3 attempts.
    ///
    /// # Arguments
    ///
    /// * `max_attempts` - Maximum number of attempts (including the initial attempt)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// // Critical job that should be retried many times
    /// let job = Job::new("critical_task".to_string(), json!({"task": "important"}))
    ///     .with_max_attempts(10);
    ///
    /// assert_eq!(job.max_attempts, 10);
    /// ```
    pub fn with_max_attempts(mut self, max_attempts: i32) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Sets a timeout duration for this job.
    ///
    /// If the job takes longer than this duration to complete, it will be
    /// automatically terminated and marked as timed out. Job-level timeouts
    /// take precedence over worker-level default timeouts.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration the job is allowed to run
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// // API call that should timeout after 30 seconds
    /// let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.com"}))
    ///     .with_timeout(Duration::from_secs(30));
    ///
    /// assert_eq!(job.timeout, Some(Duration::from_secs(30)));
    /// ```
    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets the priority level for this job.
    ///
    /// Priority affects the order in which jobs are processed by workers.
    /// Higher priority jobs are generally processed before lower priority ones.
    ///
    /// # Arguments
    ///
    /// * `priority` - The priority level to assign to this job
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("task".to_string(), json!({"data": "test"}))
    ///     .with_priority(JobPriority::High);
    ///
    /// assert_eq!(job.priority, JobPriority::High);
    /// assert!(job.is_high_priority());
    /// ```
    pub fn with_priority(mut self, priority: JobPriority) -> Self {
        self.priority = priority;
        self
    }

    /// Sets the job as critical priority (highest priority).
    ///
    /// Critical jobs are processed with the highest priority and should be used
    /// sparingly for truly urgent work like system alerts or emergency responses.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("system_alert".to_string(), json!({"alert": "system_down"}))
    ///     .as_critical();
    ///
    /// assert_eq!(job.priority, JobPriority::Critical);
    /// assert!(job.is_critical());
    /// ```
    pub fn as_critical(mut self) -> Self {
        self.priority = JobPriority::Critical;
        self
    }

    /// Sets the job as high priority.
    ///
    /// High priority jobs are processed before normal priority jobs but after
    /// critical jobs. Suitable for user-facing operations or important business logic.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("user_notification".to_string(), json!({"user_id": 123}))
    ///     .as_high_priority();
    ///
    /// assert_eq!(job.priority, JobPriority::High);
    /// assert!(job.is_high_priority());
    /// ```
    pub fn as_high_priority(mut self) -> Self {
        self.priority = JobPriority::High;
        self
    }

    /// Sets the job as low priority.
    ///
    /// Low priority jobs are processed after normal priority jobs but before
    /// background jobs. Suitable for analytics, reporting, or non-urgent tasks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("analytics".to_string(), json!({"event": "page_view"}))
    ///     .as_low_priority();
    ///
    /// assert_eq!(job.priority, JobPriority::Low);
    /// assert!(job.is_low_priority());
    /// ```
    pub fn as_low_priority(mut self) -> Self {
        self.priority = JobPriority::Low;
        self
    }

    /// Sets the job as background priority (lowest priority).
    ///
    /// Background jobs are processed only when no higher priority jobs are available.
    /// Suitable for cleanup tasks, maintenance, or work that can wait indefinitely.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, JobPriority};
    /// use serde_json::json;
    ///
    /// let job = Job::new("cleanup".to_string(), json!({"type": "temp_files"}))
    ///     .as_background();
    ///
    /// assert_eq!(job.priority, JobPriority::Background);
    /// assert!(job.is_background());
    /// ```
    pub fn as_background(mut self) -> Self {
        self.priority = JobPriority::Background;
        self
    }

    /// Sets a custom retry strategy for this job.
    ///
    /// The retry strategy determines how long to wait between retry attempts
    /// when the job fails. This overrides any default retry strategy configured
    /// on the worker.
    ///
    /// # Arguments
    ///
    /// * `strategy` - The retry strategy to use for this job
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, retry::RetryStrategy};
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// // Use exponential backoff for API calls
    /// let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.com"}))
    ///     .with_retry_strategy(RetryStrategy::exponential(
    ///         Duration::from_secs(1),
    ///         2.0,
    ///         Some(Duration::from_secs(10 * 60))
    ///     ));
    /// ```
    pub fn with_retry_strategy(mut self, strategy: RetryStrategy) -> Self {
        self.retry_strategy = Some(strategy);
        self
    }

    /// Sets exponential backoff retry strategy for this job.
    ///
    /// This is a convenience method for the most common retry pattern.
    /// Each retry attempt waits exponentially longer than the previous one.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay for the first retry attempt
    /// * `multiplier` - Exponential growth multiplier (typically 2.0)
    /// * `max_delay` - Maximum delay to cap exponential growth
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// // Exponential backoff: 1s, 2s, 4s, 8s, 16s... (capped at 10 minutes)
    /// let job = Job::new("network_request".to_string(), json!({"url": "https://example.com"}))
    ///     .with_exponential_backoff(
    ///         Duration::from_secs(1),
    ///         2.0,
    ///         Duration::from_secs(10 * 60)
    ///     );
    /// ```
    pub fn with_exponential_backoff(
        mut self,
        base: std::time::Duration,
        multiplier: f64,
        max_delay: std::time::Duration,
    ) -> Self {
        self.retry_strategy = Some(RetryStrategy::exponential(
            base,
            multiplier,
            Some(max_delay),
        ));
        self
    }

    /// Sets linear backoff retry strategy for this job.
    ///
    /// Each retry attempt waits longer than the previous by a fixed increment.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay for the first retry attempt
    /// * `increment` - Amount to add for each subsequent attempt
    /// * `max_delay` - Optional maximum delay to cap growth
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// // Linear backoff: 10s, 20s, 30s, 40s... (capped at 2 minutes)
    /// let job = Job::new("database_operation".to_string(), json!({"query": "SELECT ..."}))
    ///     .with_linear_backoff(
    ///         Duration::from_secs(10),
    ///         Duration::from_secs(10),
    ///         Some(Duration::from_secs(2 * 60))
    ///     );
    /// ```
    pub fn with_linear_backoff(
        mut self,
        base: std::time::Duration,
        increment: std::time::Duration,
        max_delay: Option<std::time::Duration>,
    ) -> Self {
        self.retry_strategy = Some(RetryStrategy::linear(base, increment, max_delay));
        self
    }

    /// Sets Fibonacci sequence backoff retry strategy for this job.
    ///
    /// Each retry waits according to the Fibonacci sequence multiplied by the base delay.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay multiplied by Fibonacci numbers
    /// * `max_delay` - Optional maximum delay to cap growth
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// // Fibonacci backoff: 2s, 2s, 4s, 6s, 10s, 16s, 26s...
    /// let job = Job::new("file_processing".to_string(), json!({"file": "data.csv"}))
    ///     .with_fibonacci_backoff(
    ///         Duration::from_secs(2),
    ///         Some(Duration::from_secs(5 * 60))
    ///     );
    /// ```
    pub fn with_fibonacci_backoff(
        mut self,
        base: std::time::Duration,
        max_delay: Option<std::time::Duration>,
    ) -> Self {
        self.retry_strategy = Some(RetryStrategy::fibonacci(base, max_delay));
        self
    }

    /// Create a recurring job with a cron schedule
    pub fn with_cron_schedule(
        queue_name: String,
        payload: serde_json::Value,
        cron_schedule: CronSchedule,
    ) -> Result<Self, crate::cron::CronError> {
        let now = Utc::now();
        let next_run = cron_schedule.next_execution_from_now();

        Ok(Self {
            id: Uuid::new_v4(),
            queue_name,
            payload,
            status: JobStatus::Pending,
            attempts: 0,
            max_attempts: 3,
            created_at: now,
            scheduled_at: next_run.unwrap_or(now),
            started_at: None,
            completed_at: None,
            failed_at: None,
            timed_out_at: None,
            timeout: None,
            error_message: None,
            priority: JobPriority::default(),
            cron_schedule: Some(cron_schedule.expression.clone()),
            next_run_at: next_run,
            recurring: true,
            timezone: Some(cron_schedule.timezone.clone()),
            batch_id: None,
            result_config: ResultConfig::default(),
            result_data: None,
            result_stored_at: None,
            result_expires_at: None,
            retry_strategy: None,
            depends_on: Vec::new(),
            dependents: Vec::new(),
            dependency_status: crate::workflow::DependencyStatus::None,
            workflow_id: None,
            workflow_name: None,
            trace_id: None,
            correlation_id: None,
            parent_span_id: None,
            span_context: None,
            #[cfg(feature = "encryption")]
            encryption_config: None,
            pii_fields: Vec::new(),
            #[cfg(feature = "encryption")]
            retention_policy: None,
            is_encrypted: false,
            #[cfg(feature = "encryption")]
            encrypted_payload: None,
        })
    }

    /// Add a cron schedule to an existing job
    pub fn with_cron(
        mut self,
        cron_schedule: CronSchedule,
    ) -> Result<Self, crate::cron::CronError> {
        let next_run = cron_schedule.next_execution_from_now();
        self.cron_schedule = Some(cron_schedule.expression.clone());
        self.next_run_at = next_run;
        self.recurring = true;
        self.timezone = Some(cron_schedule.timezone.clone());
        self.scheduled_at = next_run.unwrap_or(self.scheduled_at);
        Ok(self)
    }

    /// Set the job as recurring without a cron schedule (for manual rescheduling)
    pub fn as_recurring(mut self) -> Self {
        self.recurring = true;
        self
    }

    /// Set the timezone for the job
    pub fn with_timezone(mut self, timezone: String) -> Self {
        self.timezone = Some(timezone);
        self
    }

    /// Configure how job results should be stored.
    ///
    /// This allows jobs to store their results for later retrieval by other systems.
    /// Results can be stored in the database, memory, or not stored at all.
    ///
    /// # Arguments
    ///
    /// * `storage` - The storage backend to use for results
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, job::ResultStorage};
    /// use serde_json::json;
    ///
    /// let job = Job::new("data_processing".to_string(), json!({"input": "data"}))
    ///     .with_result_storage(ResultStorage::Database);
    /// ```
    pub fn with_result_storage(mut self, storage: ResultStorage) -> Self {
        self.result_config.storage = storage;
        self
    }

    /// Set the time-to-live (TTL) for stored job results.
    ///
    /// After this duration elapses, the result will be eligible for cleanup.
    /// This is useful for managing storage costs and compliance requirements.
    ///
    /// # Arguments
    ///
    /// * `ttl` - How long to keep results before they expire
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// let job = Job::new("report_generation".to_string(), json!({"type": "monthly"}))
    ///     .with_result_ttl(Duration::from_secs(7 * 24 * 60 * 60)); // 7 days
    /// ```
    pub fn with_result_ttl(mut self, ttl: std::time::Duration) -> Self {
        self.result_config.ttl = Some(ttl);
        self
    }

    /// Configure complete result storage settings.
    ///
    /// This provides full control over how results are stored and managed.
    ///
    /// # Arguments
    ///
    /// * `config` - Complete result configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, job::{ResultConfig, ResultStorage}};
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// let config = ResultConfig::new(ResultStorage::Database)
    ///     .with_ttl(Duration::from_secs(3600))
    ///     .with_max_size(1024 * 1024); // 1MB
    ///
    /// let job = Job::new("large_processing".to_string(), json!({"data": "..."}))
    ///     .with_result_config(config);
    /// ```
    pub fn with_result_config(mut self, config: ResultConfig) -> Self {
        self.result_config = config;
        self
    }

    /// Check if the job has result storage configured.
    ///
    /// Returns `true` if the job is configured to store results in any backend
    /// other than `ResultStorage::None`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::{Job, job::ResultStorage};
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("test".to_string(), json!({}));
    /// assert!(!job1.has_result_storage());
    ///
    /// let job2 = Job::new("test".to_string(), json!({}))
    ///     .with_result_storage(ResultStorage::Database);
    /// assert!(job2.has_result_storage());
    /// ```
    pub fn has_result_storage(&self) -> bool {
        self.result_config.storage != ResultStorage::None
    }

    /// Check if the job has stored result data.
    ///
    /// Returns `true` if the job has result data available for retrieval.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}));
    /// assert!(!job.has_result_data());
    /// ```
    pub fn has_result_data(&self) -> bool {
        self.result_data.is_some()
    }

    /// Check if the job is dead (failed all retry attempts)
    pub fn is_dead(&self) -> bool {
        self.status == JobStatus::Dead
    }

    /// Check if the job has timed out
    pub fn is_timed_out(&self) -> bool {
        self.status == JobStatus::TimedOut
    }

    /// Check if the job is critical priority
    pub fn is_critical(&self) -> bool {
        self.priority == JobPriority::Critical
    }

    /// Check if the job is high priority
    pub fn is_high_priority(&self) -> bool {
        self.priority == JobPriority::High
    }

    /// Check if the job is normal priority
    pub fn is_normal_priority(&self) -> bool {
        self.priority == JobPriority::Normal
    }

    /// Check if the job is low priority
    pub fn is_low_priority(&self) -> bool {
        self.priority == JobPriority::Low
    }

    /// Check if the job is background priority
    pub fn is_background(&self) -> bool {
        self.priority == JobPriority::Background
    }

    /// Get the priority level as a numeric value for comparison
    pub fn priority_value(&self) -> i32 {
        self.priority.as_i32()
    }

    /// Check if the job has exhausted all retry attempts
    pub fn has_exhausted_retries(&self) -> bool {
        self.attempts >= self.max_attempts
    }

    /// Checks if the job should timeout based on its start time and timeout setting.
    ///
    /// Returns `true` if the job has been running longer than its configured timeout
    /// duration. Returns `false` if the job hasn't started yet, has no timeout set,
    /// or is still within the timeout window.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use std::time::Duration;
    /// use chrono::Utc;
    ///
    /// let mut job = Job::new("test".to_string(), json!({"data": "test"}))
    ///     .with_timeout(Duration::from_secs(30));
    ///
    /// // Job hasn't started yet, so it shouldn't timeout
    /// assert!(!job.should_timeout());
    ///
    /// // Simulate job starting 45 seconds ago
    /// job.started_at = Some(Utc::now() - chrono::Duration::seconds(45));
    ///
    /// // Job should timeout since 45s > 30s timeout
    /// assert!(job.should_timeout());
    /// ```
    pub fn should_timeout(&self) -> bool {
        if let (Some(started_at), Some(timeout)) = (self.started_at, self.timeout) {
            let elapsed = Utc::now() - started_at;
            let timeout_duration = chrono::Duration::from_std(timeout).unwrap_or_default();
            elapsed >= timeout_duration
        } else {
            false
        }
    }

    /// Gets the duration since the job was created.
    ///
    /// This is useful for monitoring how long jobs have been in the system
    /// and identifying jobs that may be stuck or delayed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({"data": "test"}));
    /// let age = job.age();
    ///
    /// // Job was just created, so age should be very small
    /// assert!(age.num_milliseconds() >= 0);
    /// assert!(age.num_seconds() < 1);
    /// ```
    pub fn age(&self) -> chrono::Duration {
        Utc::now() - self.created_at
    }

    /// Gets the processing duration if the job has started.
    ///
    /// Returns the time between when the job started and when it finished
    /// (completed, failed, or timed out). If the job is still running,
    /// returns the time since it started. Returns `None` if the job hasn't
    /// started yet.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use chrono::Utc;
    ///
    /// let mut job = Job::new("test".to_string(), json!({"data": "test"}));
    ///
    /// // Job hasn't started, so no processing duration
    /// assert!(job.processing_duration().is_none());
    ///
    /// // Simulate job that started and completed
    /// let start_time = Utc::now() - chrono::Duration::seconds(10);
    /// let end_time = start_time + chrono::Duration::seconds(5);
    /// job.started_at = Some(start_time);
    /// job.completed_at = Some(end_time);
    ///
    /// let duration = job.processing_duration().unwrap();
    /// assert_eq!(duration.num_seconds(), 5);
    /// ```
    pub fn processing_duration(&self) -> Option<chrono::Duration> {
        self.started_at.map(|started| {
            self.completed_at
                .or(self.failed_at)
                .or(self.timed_out_at)
                .unwrap_or_else(Utc::now)
                - started
        })
    }

    /// Check if this is a recurring job
    pub fn is_recurring(&self) -> bool {
        self.recurring
    }

    /// Check if this job has a cron schedule
    pub fn has_cron_schedule(&self) -> bool {
        self.cron_schedule.is_some()
    }

    /// Get the cron schedule if it exists
    pub fn get_cron_schedule(&self) -> Option<Result<CronSchedule, crate::cron::CronError>> {
        self.cron_schedule
            .as_ref()
            .map(|expr| match &self.timezone {
                Some(tz) => CronSchedule::with_timezone(expr, tz),
                None => CronSchedule::new(expr),
            })
    }

    /// Calculate the next run time for a recurring job
    pub fn calculate_next_run(&self) -> Option<DateTime<Utc>> {
        if !self.recurring {
            return None;
        }

        if let Some(cron_schedule) = self.get_cron_schedule() {
            match cron_schedule {
                Ok(schedule) => schedule.next_execution_from_now(),
                Err(_) => None,
            }
        } else {
            None
        }
    }

    /// Update the job for the next run (for recurring jobs)
    pub fn prepare_for_next_run(&mut self) -> Option<DateTime<Utc>> {
        if !self.recurring {
            return None;
        }

        let next_run = self.calculate_next_run();
        if let Some(next_time) = next_run {
            self.status = JobStatus::Pending;
            self.attempts = 0;
            self.scheduled_at = next_time;
            self.next_run_at = Some(next_time);
            self.started_at = None;
            self.completed_at = None;
            self.failed_at = None;
            self.timed_out_at = None;
            self.error_message = None;
        }
        next_run
    }

    /// Adds a dependency on another job.
    ///
    /// This job will not be executed until the specified job completes successfully.
    /// If the dependency job fails, this job's dependency status will be set to Failed.
    ///
    /// # Arguments
    ///
    /// * `job_id` - The ID of the job this job should depend on
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("step1".to_string(), json!({"data": "step1"}));
    /// let job2 = Job::new("step2".to_string(), json!({"data": "step2"}))
    ///     .depends_on(&job1.id);
    /// assert!(job2.has_dependencies());
    /// ```
    pub fn depends_on(mut self, job_id: &JobId) -> Self {
        self.depends_on.push(*job_id);
        self.dependency_status = crate::workflow::DependencyStatus::Waiting;
        self
    }

    /// Adds multiple dependencies on other jobs.
    ///
    /// This job will not be executed until all specified jobs complete successfully.
    ///
    /// # Arguments
    ///
    /// * `job_ids` - The IDs of the jobs this job should depend on
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("step1".to_string(), json!({}));
    /// let job2 = Job::new("step2".to_string(), json!({}));
    /// let final_job = Job::new("final".to_string(), json!({}))
    ///     .depends_on_jobs(&[job1.id, job2.id]);
    /// assert_eq!(final_job.depends_on.len(), 2);
    /// ```
    pub fn depends_on_jobs(mut self, job_ids: &[JobId]) -> Self {
        self.depends_on.extend_from_slice(job_ids);
        if !job_ids.is_empty() {
            self.dependency_status = crate::workflow::DependencyStatus::Waiting;
        }
        self
    }

    /// Sets the workflow this job belongs to.
    ///
    /// # Arguments
    ///
    /// * `workflow_id` - The ID of the workflow
    /// * `workflow_name` - The name of the workflow
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use uuid::Uuid;
    ///
    /// let workflow_id = Uuid::new_v4();
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_workflow(workflow_id, "data_pipeline");
    ///
    /// assert_eq!(job.workflow_id, Some(workflow_id));
    /// assert_eq!(job.workflow_name, Some("data_pipeline".to_string()));
    /// ```
    pub fn with_workflow(
        mut self,
        workflow_id: crate::workflow::WorkflowId,
        workflow_name: impl Into<String>,
    ) -> Self {
        self.workflow_id = Some(workflow_id);
        self.workflow_name = Some(workflow_name.into());
        self
    }

    /// Checks if this job has any dependencies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("independent".to_string(), json!({}));
    /// assert!(!job1.has_dependencies());
    ///
    /// let job2 = Job::new("dependent".to_string(), json!({}))
    ///     .depends_on(&job1.id);
    /// assert!(job2.has_dependencies());
    /// ```
    pub fn has_dependencies(&self) -> bool {
        !self.depends_on.is_empty()
    }

    /// Checks if this job is part of a workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use uuid::Uuid;
    ///
    /// let job1 = Job::new("standalone".to_string(), json!({}));
    /// assert!(!job1.is_part_of_workflow());
    ///
    /// let job2 = Job::new("workflow_job".to_string(), json!({}))
    ///     .with_workflow(Uuid::new_v4(), "test_workflow");
    /// assert!(job2.is_part_of_workflow());
    /// ```
    pub fn is_part_of_workflow(&self) -> bool {
        self.workflow_id.is_some()
    }

    /// Checks if all dependencies for this job are satisfied.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("independent".to_string(), json!({}));
    /// assert!(job1.dependencies_satisfied());
    ///
    /// let job2 = Job::new("dependent".to_string(), json!({}))
    ///     .depends_on(&job1.id);
    /// assert!(!job2.dependencies_satisfied()); // Dependencies not satisfied yet
    /// ```
    pub fn dependencies_satisfied(&self) -> bool {
        matches!(
            self.dependency_status,
            crate::workflow::DependencyStatus::None | crate::workflow::DependencyStatus::Satisfied
        )
    }

    /// Checks if any dependencies for this job have failed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let mut job = Job::new("test".to_string(), json!({}));
    /// job.dependency_status = hammerwork::workflow::DependencyStatus::Failed;
    /// assert!(job.dependencies_failed());
    /// ```
    pub fn dependencies_failed(&self) -> bool {
        matches!(
            self.dependency_status,
            crate::workflow::DependencyStatus::Failed
        )
    }

    /// Gets the number of dependencies for this job.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    /// use uuid::Uuid;
    ///
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .depends_on_jobs(&[Uuid::new_v4(), Uuid::new_v4()]);
    /// assert_eq!(job.dependency_count(), 2);
    /// ```
    pub fn dependency_count(&self) -> usize {
        self.depends_on.len()
    }

    /// Gets the number of jobs that depend on this job.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}));
    /// assert_eq!(job.dependent_count(), 0);
    /// ```
    pub fn dependent_count(&self) -> usize {
        self.dependents.len()
    }

    /// Sets the distributed trace identifier for this job.
    ///
    /// The trace ID is used to track jobs across service boundaries in distributed
    /// systems. All related operations should share the same trace ID.
    ///
    /// # Arguments
    ///
    /// * `trace_id` - The distributed trace identifier
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("service_call".to_string(), json!({"data": "test"}))
    ///     .with_trace_id("trace-123-456");
    ///
    /// assert_eq!(job.trace_id, Some("trace-123-456".to_string()));
    /// ```
    pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self
    }

    /// Sets the business correlation identifier for this job.
    ///
    /// The correlation ID groups related business operations together, even if they
    /// span multiple traces or services. Use this to correlate jobs that process
    /// the same business entity or workflow.
    ///
    /// # Arguments
    ///
    /// * `correlation_id` - The business correlation identifier
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("order_processing".to_string(), json!({"order_id": 12345}))
    ///     .with_correlation_id("order-12345");
    ///
    /// assert_eq!(job.correlation_id, Some("order-12345".to_string()));
    /// ```
    pub fn with_correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
        self.correlation_id = Some(correlation_id.into());
        self
    }

    /// Sets the parent span identifier for hierarchical tracing.
    ///
    /// Use this to create a parent-child relationship between spans, enabling
    /// hierarchical trace visualization in tracing systems.
    ///
    /// # Arguments
    ///
    /// * `parent_span_id` - The parent span identifier
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("child_task".to_string(), json!({"data": "test"}))
    ///     .with_parent_span_id("span-parent-123");
    ///
    /// assert_eq!(job.parent_span_id, Some("span-parent-123".to_string()));
    /// ```
    pub fn with_parent_span_id(mut self, parent_span_id: impl Into<String>) -> Self {
        self.parent_span_id = Some(parent_span_id.into());
        self
    }

    /// Sets the serialized span context for trace propagation.
    ///
    /// The span context contains all the information needed to propagate tracing
    /// across service boundaries. This is typically a serialized representation
    /// of the current span context.
    ///
    /// # Arguments
    ///
    /// * `span_context` - The serialized span context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("distributed_task".to_string(), json!({"data": "test"}))
    ///     .with_span_context("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
    ///
    /// assert_eq!(job.span_context, Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01".to_string()));
    /// ```
    pub fn with_span_context(mut self, span_context: impl Into<String>) -> Self {
        self.span_context = Some(span_context.into());
        self
    }

    /// Convenience method to set both trace ID and correlation ID.
    ///
    /// This is useful when the trace ID and correlation ID are the same,
    /// which is common in simple tracing scenarios.
    ///
    /// # Arguments
    ///
    /// * `id` - The identifier to use for both trace and correlation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("task".to_string(), json!({"data": "test"}))
    ///     .with_tracing_id("unified-id-123");
    ///
    /// assert_eq!(job.trace_id, Some("unified-id-123".to_string()));
    /// assert_eq!(job.correlation_id, Some("unified-id-123".to_string()));
    /// ```
    pub fn with_tracing_id(mut self, id: impl Into<String>) -> Self {
        let id_string = id.into();
        self.trace_id = Some(id_string.clone());
        self.correlation_id = Some(id_string);
        self
    }

    /// Checks if this job has any tracing information.
    ///
    /// Returns `true` if any of the tracing fields (trace_id, correlation_id,
    /// parent_span_id, or span_context) are set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("untraced".to_string(), json!({}));
    /// assert!(!job1.has_tracing_info());
    ///
    /// let job2 = Job::new("traced".to_string(), json!({}))
    ///     .with_trace_id("trace-123");
    /// assert!(job2.has_tracing_info());
    /// ```
    pub fn has_tracing_info(&self) -> bool {
        self.trace_id.is_some()
            || self.correlation_id.is_some()
            || self.parent_span_id.is_some()
            || self.span_context.is_some()
    }

    /// Gets the trace ID if available.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_trace_id("trace-123");
    ///
    /// assert_eq!(job.get_trace_id(), Some("trace-123"));
    /// ```
    pub fn get_trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    /// Gets the correlation ID if available.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_correlation_id("corr-456");
    ///
    /// assert_eq!(job.get_correlation_id(), Some("corr-456"));
    /// ```
    pub fn get_correlation_id(&self) -> Option<&str> {
        self.correlation_id.as_deref()
    }

    /// Sets the encryption configuration for this job.
    ///
    /// When encryption is configured, the job payload will be encrypted before
    /// being stored in the database and decrypted when retrieved.
    ///
    /// # Arguments
    ///
    /// * `config` - The encryption configuration to use
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::{Job, encryption::{EncryptionConfig, EncryptionAlgorithm}};
    /// use serde_json::json;
    ///
    /// let job = Job::new("secure_task".to_string(), json!({"data": "sensitive"}))
    ///     .with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM));
    ///
    /// assert!(job.has_encryption());
    /// # }
    /// ```
    #[cfg(feature = "encryption")]
    pub fn with_encryption(mut self, config: crate::encryption::EncryptionConfig) -> Self {
        self.encryption_config = Some(config);
        self
    }

    /// Sets the PII fields for this job.
    ///
    /// PII (Personally Identifiable Information) fields are tracked separately
    /// for compliance and auditing purposes. When encryption is enabled, these
    /// fields receive special handling.
    ///
    /// # Arguments
    ///
    /// * `pii_fields` - List of field names that contain PII
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("user_processing".to_string(), json!({
    ///     "user_id": "123",
    ///     "email": "user@example.com",
    ///     "ssn": "123-45-6789"
    /// }))
    /// .with_pii_fields(vec!["email", "ssn"]);
    ///
    /// assert_eq!(job.pii_fields.len(), 2);
    /// assert!(job.has_pii_fields());
    /// ```
    pub fn with_pii_fields(mut self, pii_fields: Vec<impl Into<String>>) -> Self {
        self.pii_fields = pii_fields.into_iter().map(|f| f.into()).collect();
        self
    }

    /// Sets the retention policy for this job's encrypted data.
    ///
    /// The retention policy determines how long encrypted job data should be
    /// kept before automatic cleanup.
    ///
    /// # Arguments
    ///
    /// * `policy` - The retention policy to apply
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::{Job, encryption::RetentionPolicy};
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// let job = Job::new("temp_processing".to_string(), json!({"data": "temp"}))
    ///     .with_retention_policy(RetentionPolicy::DeleteAfter(Duration::from_secs(3600)));
    /// # }
    /// ```
    #[cfg(feature = "encryption")]
    pub fn with_retention_policy(mut self, policy: crate::encryption::RetentionPolicy) -> Self {
        self.retention_policy = Some(policy);
        self
    }

    /// Checks if this job has encryption configured.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("plain".to_string(), json!({}));
    /// assert!(!job1.has_encryption());
    ///
    /// #[cfg(feature = "encryption")]
    /// {
    ///     use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///     let job2 = Job::new("encrypted".to_string(), json!({}))
    ///         .with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM));
    ///     assert!(job2.has_encryption());
    /// }
    /// ```
    pub fn has_encryption(&self) -> bool {
        #[cfg(feature = "encryption")]
        {
            self.encryption_config.is_some()
        }
        #[cfg(not(feature = "encryption"))]
        {
            false
        }
    }

    /// Checks if this job has PII fields configured.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job1 = Job::new("normal".to_string(), json!({}));
    /// assert!(!job1.has_pii_fields());
    ///
    /// let job2 = Job::new("with_pii".to_string(), json!({}))
    ///     .with_pii_fields(vec!["email"]);
    /// assert!(job2.has_pii_fields());
    /// ```
    pub fn has_pii_fields(&self) -> bool {
        !self.pii_fields.is_empty()
    }

    /// Checks if this job's payload is currently encrypted.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}));
    /// assert!(!job.is_payload_encrypted());
    /// ```
    pub fn is_payload_encrypted(&self) -> bool {
        self.is_encrypted
    }

    /// Gets the list of PII fields for this job.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_pii_fields(vec!["email", "ssn"]);
    ///
    /// let pii_fields = job.get_pii_fields();
    /// assert_eq!(pii_fields.len(), 2);
    /// assert!(pii_fields.contains(&"email".to_string()));
    /// ```
    pub fn get_pii_fields(&self) -> &[String] {
        &self.pii_fields
    }

    /// Gets the encryption configuration if available.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::{Job, encryption::{EncryptionConfig, EncryptionAlgorithm}};
    /// use serde_json::json;
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_encryption(config.clone());
    ///
    /// let retrieved_config = job.get_encryption_config().unwrap();
    /// assert_eq!(retrieved_config.algorithm, EncryptionAlgorithm::AES256GCM);
    /// # }
    /// ```
    #[cfg(feature = "encryption")]
    pub fn get_encryption_config(&self) -> Option<&crate::encryption::EncryptionConfig> {
        self.encryption_config.as_ref()
    }

    /// Gets the retention policy if available.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::{Job, encryption::RetentionPolicy};
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// let policy = RetentionPolicy::DeleteAfter(Duration::from_secs(3600));
    /// let job = Job::new("test".to_string(), json!({}))
    ///     .with_retention_policy(policy.clone());
    ///
    /// assert_eq!(job.get_retention_policy(), Some(&policy));
    /// # }
    /// ```
    #[cfg(feature = "encryption")]
    pub fn get_retention_policy(&self) -> Option<&crate::encryption::RetentionPolicy> {
        self.retention_policy.as_ref()
    }

    /// Checks if this job should have its encrypted data cleaned up now.
    ///
    /// This method checks the retention policy and encrypted payload metadata
    /// to determine if the data has exceeded its retention period.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::Job;
    /// use serde_json::json;
    ///
    /// let job = Job::new("test".to_string(), json!({}));
    /// assert!(!job.should_cleanup_encrypted_data());
    /// ```
    pub fn should_cleanup_encrypted_data(&self) -> bool {
        #[cfg(feature = "encryption")]
        {
            if let Some(encrypted_payload) = &self.encrypted_payload {
                encrypted_payload.should_delete_now()
            } else if let Some(retention_policy) = &self.retention_policy {
                retention_policy.should_delete_now(
                    self.created_at,
                    self.completed_at,
                    self.encryption_config
                        .as_ref()
                        .and_then(|c| c.default_retention),
                )
            } else {
                false
            }
        }
        #[cfg(not(feature = "encryption"))]
        {
            false
        }
    }
}

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

    #[test]
    fn test_job_new() {
        let queue_name = "test_queue".to_string();
        let payload = json!({"key": "value"});

        let job = Job::new(queue_name.clone(), payload.clone());

        assert_eq!(job.queue_name, queue_name);
        assert_eq!(job.payload, payload);
        assert_eq!(job.status, JobStatus::Pending);
        assert_eq!(job.attempts, 0);
        assert_eq!(job.max_attempts, 3);
        assert!(job.started_at.is_none());
        assert!(job.completed_at.is_none());
        assert!(job.failed_at.is_none());
        assert!(job.error_message.is_none());
        assert_eq!(job.created_at, job.scheduled_at);
    }

    #[test]
    fn test_job_with_delay() {
        let queue_name = "test_queue".to_string();
        let payload = json!({"key": "value"});
        let delay = chrono::Duration::minutes(5);

        let job = Job::with_delay(queue_name.clone(), payload.clone(), delay);

        assert_eq!(job.queue_name, queue_name);
        assert_eq!(job.payload, payload);
        assert_eq!(job.status, JobStatus::Pending);
        assert_eq!(job.attempts, 0);
        assert_eq!(job.max_attempts, 3);
        assert!(job.scheduled_at > job.created_at);
        assert_eq!(job.scheduled_at - job.created_at, delay);
    }

    #[test]
    fn test_job_with_max_attempts() {
        let queue_name = "test_queue".to_string();
        let payload = json!({"key": "value"});

        let job = Job::new(queue_name, payload).with_max_attempts(5);

        assert_eq!(job.max_attempts, 5);
    }

    #[test]
    fn test_job_with_delay_and_max_attempts() {
        let queue_name = "test_queue".to_string();
        let payload = json!({"key": "value"});
        let delay = chrono::Duration::hours(1);

        let job = Job::with_delay(queue_name, payload, delay).with_max_attempts(10);

        assert_eq!(job.max_attempts, 10);
        assert!(job.scheduled_at > job.created_at);
    }

    #[test]
    fn test_job_status_equality() {
        assert_eq!(JobStatus::Pending, JobStatus::Pending);
        assert_eq!(JobStatus::Running, JobStatus::Running);
        assert_eq!(JobStatus::Completed, JobStatus::Completed);
        assert_eq!(JobStatus::Failed, JobStatus::Failed);
        assert_eq!(JobStatus::Dead, JobStatus::Dead);
        assert_eq!(JobStatus::TimedOut, JobStatus::TimedOut);
        assert_eq!(JobStatus::Retrying, JobStatus::Retrying);

        assert_ne!(JobStatus::Pending, JobStatus::Running);
        assert_ne!(JobStatus::Completed, JobStatus::Failed);
        assert_ne!(JobStatus::Failed, JobStatus::Dead);
        assert_ne!(JobStatus::Dead, JobStatus::TimedOut);
        assert_ne!(JobStatus::TimedOut, JobStatus::Failed);
    }

    #[test]
    fn test_job_serialization() {
        let job = Job::new("test".to_string(), json!({"data": "test"}));

        let serialized = serde_json::to_string(&job).unwrap();
        let deserialized: Job = serde_json::from_str(&serialized).unwrap();

        assert_eq!(job.id, deserialized.id);
        assert_eq!(job.queue_name, deserialized.queue_name);
        assert_eq!(job.payload, deserialized.payload);
        assert_eq!(job.status, deserialized.status);
        assert_eq!(job.attempts, deserialized.attempts);
        assert_eq!(job.max_attempts, deserialized.max_attempts);
    }

    #[test]
    fn test_job_status_serialization() {
        let statuses = vec![
            JobStatus::Pending,
            JobStatus::Running,
            JobStatus::Completed,
            JobStatus::Failed,
            JobStatus::Dead,
            JobStatus::TimedOut,
            JobStatus::Retrying,
        ];

        for status in statuses {
            let serialized = serde_json::to_string(&status).unwrap();
            let deserialized: JobStatus = serde_json::from_str(&serialized).unwrap();
            assert_eq!(status, deserialized);
        }
    }

    #[test]
    fn test_job_dead_status_methods() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // Initially not dead
        assert!(!job.is_dead());
        assert!(!job.has_exhausted_retries());

        // Simulate exhausting retries
        job.attempts = 3;
        job.max_attempts = 3;
        assert!(job.has_exhausted_retries());
        assert!(!job.is_dead()); // Still not dead until status is set

        // Mark as dead
        job.status = JobStatus::Dead;
        job.failed_at = Some(Utc::now());
        assert!(job.is_dead());
        assert!(job.has_exhausted_retries());
    }

    #[test]
    fn test_job_processing_duration() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // No processing duration when not started
        assert!(job.processing_duration().is_none());

        // Set start time
        let start_time = Utc::now();
        job.started_at = Some(start_time);

        // Should have some duration now (very small)
        let duration = job.processing_duration().unwrap();
        assert!(duration.num_milliseconds() >= 0);

        // Set completion time
        let completion_time = start_time + chrono::Duration::seconds(5);
        job.completed_at = Some(completion_time);

        let final_duration = job.processing_duration().unwrap();
        assert_eq!(final_duration.num_seconds(), 5);
    }

    #[test]
    fn test_job_age() {
        let job = Job::new("test".to_string(), json!({"data": "test"}));
        let age = job.age();

        // Age should be very small (just created)
        assert!(age.num_milliseconds() >= 0);
        assert!(age.num_seconds() < 1);
    }

    #[test]
    fn test_job_with_timeout() {
        let timeout = std::time::Duration::from_secs(30);
        let job = Job::new("test".to_string(), json!({"data": "test"})).with_timeout(timeout);

        assert_eq!(job.timeout, Some(timeout));
        assert!(!job.is_timed_out()); // Not timed out until status is set
    }

    #[test]
    fn test_job_timeout_status_methods() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // Initially not timed out
        assert!(!job.is_timed_out());

        // Set timed out status
        job.status = JobStatus::TimedOut;
        job.timed_out_at = Some(Utc::now());
        assert!(job.is_timed_out());
    }

    #[test]
    fn test_job_should_timeout() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}))
            .with_timeout(std::time::Duration::from_millis(100));

        // Should not timeout before it starts
        assert!(!job.should_timeout());

        // Set start time to simulate job starting
        job.started_at = Some(Utc::now() - chrono::Duration::milliseconds(200));

        // Should timeout since 200ms > 100ms timeout
        assert!(job.should_timeout());

        // Job without timeout should never timeout
        let mut job_no_timeout = Job::new("test".to_string(), json!({"data": "test"}));
        job_no_timeout.started_at = Some(Utc::now() - chrono::Duration::hours(1));
        assert!(!job_no_timeout.should_timeout());
    }

    #[test]
    fn test_job_with_delay_and_timeout() {
        let delay = chrono::Duration::minutes(5);
        let timeout = std::time::Duration::from_secs(120);

        let job = Job::with_delay("test".to_string(), json!({"data": "test"}), delay)
            .with_timeout(timeout)
            .with_max_attempts(5);

        assert_eq!(job.timeout, Some(timeout));
        assert_eq!(job.max_attempts, 5);
        assert!(job.scheduled_at > job.created_at);
        assert_eq!(job.scheduled_at - job.created_at, delay);
    }

    #[test]
    fn test_processing_duration_with_timeout() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // Set start time and timed out time
        let start_time = Utc::now() - chrono::Duration::seconds(5);
        let timeout_time = start_time + chrono::Duration::seconds(3);

        job.started_at = Some(start_time);
        job.timed_out_at = Some(timeout_time);

        let duration = job.processing_duration().unwrap();
        assert_eq!(duration.num_seconds(), 3);
    }

    #[test]
    fn test_timeout_builder_methods() {
        let job = Job::new("test".to_string(), json!({"key": "value"}))
            .with_timeout(std::time::Duration::from_secs(120))
            .with_max_attempts(5);

        assert_eq!(job.timeout, Some(std::time::Duration::from_secs(120)));
        assert_eq!(job.max_attempts, 5);
        assert_eq!(job.queue_name, "test");
    }

    #[test]
    fn test_job_timeout_edge_cases() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // Job without timeout should never timeout
        assert!(!job.should_timeout());

        // Job with timeout but not started should not timeout
        job.timeout = Some(std::time::Duration::from_millis(100));
        assert!(!job.should_timeout());

        // Job with timeout and started but within timeout window should not timeout
        job.started_at = Some(Utc::now() - chrono::Duration::milliseconds(50));
        assert!(!job.should_timeout());

        // Job with timeout and started beyond timeout window should timeout
        job.started_at = Some(Utc::now() - chrono::Duration::milliseconds(150));
        assert!(job.should_timeout());
    }

    #[test]
    fn test_job_status_transitions_with_timeout() {
        let mut job = Job::new("test".to_string(), json!({"data": "test"}));

        // Initial state
        assert_eq!(job.status, JobStatus::Pending);
        assert!(!job.is_timed_out());

        // Simulate timeout
        job.status = JobStatus::TimedOut;
        job.timed_out_at = Some(Utc::now());

        assert!(job.is_timed_out());
        assert!(!job.is_dead()); // TimedOut is different from Dead
    }

    #[test]
    fn test_timeout_serialization_compatibility() {
        let original_job = Job::new("test_queue".to_string(), json!({"data": "test"}))
            .with_timeout(std::time::Duration::from_secs(300))
            .with_max_attempts(5);

        // Serialize and deserialize
        let serialized = serde_json::to_string(&original_job).unwrap();
        let deserialized: Job = serde_json::from_str(&serialized).unwrap();

        // Verify timeout field is preserved
        assert_eq!(original_job.timeout, deserialized.timeout);
        assert_eq!(original_job.timed_out_at, deserialized.timed_out_at);
        assert_eq!(original_job.status, deserialized.status);
    }

    #[test]
    fn test_job_with_all_timeout_fields() {
        let timeout_duration = std::time::Duration::from_secs(60);
        let mut job = Job::new("comprehensive_test".to_string(), json!({"test": true}))
            .with_timeout(timeout_duration)
            .with_max_attempts(3);

        // Simulate job lifecycle with timeout
        job.started_at = Some(Utc::now() - chrono::Duration::seconds(30));
        job.status = JobStatus::Running;

        // Should not timeout yet (30s < 60s)
        assert!(!job.should_timeout());

        // Simulate timeout occurring
        job.status = JobStatus::TimedOut;
        job.timed_out_at = Some(Utc::now());
        job.error_message = Some("Job timed out after 60s".to_string());

        assert!(job.is_timed_out());
        assert_eq!(job.timeout, Some(timeout_duration));
        assert!(job.timed_out_at.is_some());
        assert!(job.error_message.is_some());
    }

    #[test]
    fn test_job_status_backward_compatibility_string_matching() {
        // Test that our string matching logic handles both quoted and unquoted formats
        // This simulates what happens in the Decode implementation
        let test_cases = [
            // (input_string, expected_status)
            ("Pending", JobStatus::Pending),
            ("\"Pending\"", JobStatus::Pending),
            ("Running", JobStatus::Running),
            ("\"Running\"", JobStatus::Running),
            ("Completed", JobStatus::Completed),
            ("\"Completed\"", JobStatus::Completed),
            ("Failed", JobStatus::Failed),
            ("\"Failed\"", JobStatus::Failed),
            ("Dead", JobStatus::Dead),
            ("\"Dead\"", JobStatus::Dead),
            ("TimedOut", JobStatus::TimedOut),
            ("\"TimedOut\"", JobStatus::TimedOut),
            ("Retrying", JobStatus::Retrying),
            ("\"Retrying\"", JobStatus::Retrying),
            ("Archived", JobStatus::Archived),
            ("\"Archived\"", JobStatus::Archived),
        ];

        for (input, expected) in &test_cases {
            // This is the same logic used in our Decode implementations
            let cleaned_str = input.trim_matches('"');
            let parsed_status = match cleaned_str {
                "Pending" => JobStatus::Pending,
                "Running" => JobStatus::Running,
                "Completed" => JobStatus::Completed,
                "Failed" => JobStatus::Failed,
                "Dead" => JobStatus::Dead,
                "TimedOut" => JobStatus::TimedOut,
                "Retrying" => JobStatus::Retrying,
                "Archived" => JobStatus::Archived,
                _ => panic!("Unknown job status: {}", input),
            };

            assert_eq!(
                *expected, parsed_status,
                "Failed to parse '{}' correctly",
                input
            );
        }
    }

    #[test]
    fn test_job_status_encoding_logic() {
        // Verify that our encoding logic produces the expected unquoted strings
        let statuses = [
            (JobStatus::Pending, "Pending"),
            (JobStatus::Running, "Running"),
            (JobStatus::Completed, "Completed"),
            (JobStatus::Failed, "Failed"),
            (JobStatus::Dead, "Dead"),
            (JobStatus::TimedOut, "TimedOut"),
            (JobStatus::Retrying, "Retrying"),
            (JobStatus::Archived, "Archived"),
        ];

        for (status, expected_str) in &statuses {
            // This matches the logic in our Encode implementations
            let encoded_str = match status {
                JobStatus::Pending => "Pending",
                JobStatus::Running => "Running",
                JobStatus::Completed => "Completed",
                JobStatus::Failed => "Failed",
                JobStatus::Dead => "Dead",
                JobStatus::TimedOut => "TimedOut",
                JobStatus::Retrying => "Retrying",
                JobStatus::Archived => "Archived",
            };

            assert_eq!(
                *expected_str, encoded_str,
                "Encoding mismatch for {:?}",
                status
            );

            // Verify the encoded string does not have quotes
            assert!(
                !encoded_str.starts_with('"'),
                "Encoded string should not start with quotes: {}",
                encoded_str
            );
            assert!(
                !encoded_str.ends_with('"'),
                "Encoded string should not end with quotes: {}",
                encoded_str
            );
        }
    }
}