cot 0.5.0

The Rust web framework for lazy developers.
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
//! Configuration data for the project.
//!
//! This module contains the configuration data for the project. This includes
//! stuff such as the secret key used for signing cookies, database connection
//! settings, whether the debug mode is enabled, and other project-specific
//! configuration data.
//!
//! The main struct in this module is [`ProjectConfig`], which contains all the
//! configuration data for the project. After creating an instance using
//! [`ProjectConfig::from_toml`] or [`ProjectConfigBuilder`], it can be passed
//! to the [`Bootstrapper`](crate::project::Bootstrapper).

// most of the config structures might be extended with non-Copy types
// in the future, so to avoid breaking backwards compatibility, we're
// not implementing Copy for them
#![allow(missing_copy_implementations)]

use std::path::PathBuf;
use std::time::Duration;

use chrono::{DateTime, FixedOffset, Utc};
use derive_builder::Builder;
use derive_more::with_trait::{Debug, From};
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use thiserror::Error;

#[cfg(feature = "email")]
use crate::email::transport::smtp::Mechanism;
use crate::error::error_impl::impl_into_cot_error;
use crate::utils::chrono::DateTimeWithOffsetAdapter;

/// The configuration for a project.
///
/// This is all the project-specific configuration data that can (and makes
/// sense to) be expressed in a TOML configuration file.
#[derive(Debug, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct ProjectConfig {
    /// Debug mode flag.
    ///
    /// This enables some expensive operations that are useful for debugging,
    /// such as logging additional information, and collecting some extra
    /// diagnostics for generating error pages. The debug flag also controls
    /// whether Cot displays nice error pages. All of this hurts the
    /// performance, so it should be disabled for production.
    ///
    /// `ProjectConfig::default()` returns `true` here when the application is
    /// compiled in debug mode, and `false` when it is compiled in release
    /// mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// debug = true
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.debug, true);
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub debug: bool,
    /// Whether to register a panic hook.
    ///
    /// The panic hook is used to display information about panics in the Cot
    /// error pages that are displayed in debug mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// register_panic_hook = false
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.register_panic_hook, false);
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub register_panic_hook: bool,
    /// The secret key used for signing cookies and other sensitive data. This
    /// is a cryptographic key, should be kept secret, and should a set to a
    /// random and unique value for each project.
    ///
    /// When you want to rotate the secret key, you can move the current key to
    /// the `fallback_secret_keys` list, and set a new key here. Eventually, you
    /// can remove the old key from the list.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// secret_key = "123abc"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.secret_key, SecretKey::from("123abc"));
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub secret_key: SecretKey,
    /// Fallback secret keys that can be used to verify old sessions.
    ///
    /// This is useful for key rotation, where you can add a new key, gradually
    /// migrate sessions to the new key, and then remove the old key.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// fallback_secret_keys = ["123abc"]
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.fallback_secret_keys, vec![SecretKey::from("123abc")]);
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub fallback_secret_keys: Vec<SecretKey>,
    /// The authentication backend to use.
    ///
    /// This is the backend that is used to authenticate users. The default is
    /// the database backend, which stores user data in the database.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, ProjectConfig};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [auth_backend]
    /// type = "none"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.auth_backend, AuthBackendConfig::None);
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub auth_backend: AuthBackendConfig,
    /// Configuration related to the database.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{AuthBackendConfig, DatabaseUrl, ProjectConfig};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [database]
    /// url = "sqlite::memory:"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(
    ///     config.database.url,
    ///     Some(DatabaseUrl::from("sqlite::memory:"))
    /// );
    /// # Ok::<(), cot::Error>(())
    /// ```
    #[cfg(feature = "db")]
    pub database: DatabaseConfig,
    /// Configuration related to the cache.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::{CacheConfig, CacheStoreTypeConfig, ProjectConfig, Timeout};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [cache]
    /// prefix = "myapp"
    /// max_retries = 3
    /// timeout = "1h"
    ///
    /// [cache.store]
    /// type = "memory"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.cache.prefix, Some("myapp".to_string()));
    /// assert_eq!(config.cache.max_retries, 3);
    /// assert_eq!(
    ///     config.cache.timeout,
    ///     Timeout::After(Duration::from_secs(3600))
    /// );
    /// assert_eq!(config.cache.store.store_type, CacheStoreTypeConfig::Memory);
    /// Ok::<(), cot::Error>(())
    /// ```
    #[cfg(feature = "cache")]
    pub cache: CacheConfig,
    /// Configuration related to the static files.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::{AuthBackendConfig, DatabaseUrl, ProjectConfig, StaticFilesPathRewriteMode};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [static_files]
    /// url = "/assets/"
    /// rewrite = "query_param"
    /// cache_timeout = "1h"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.static_files.url, "/assets/");
    /// assert_eq!(
    ///     config.static_files.rewrite,
    ///     StaticFilesPathRewriteMode::QueryParam,
    /// );
    /// assert_eq!(
    ///     config.static_files.cache_timeout,
    ///     Some(Duration::from_secs(3600)),
    /// );
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub static_files: StaticFilesConfig,
    /// Configuration related to the middlewares.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{MiddlewareConfig, ProjectConfig};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [middlewares]
    /// live_reload.enabled = true
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.middlewares.live_reload.enabled, true);
    /// # Ok::<(), cot::Error>(())
    /// ```
    pub middlewares: MiddlewareConfig,
    /// Configuration related to the email backend.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{EmailConfig, ProjectConfig};
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [email.transport]
    /// type = "console"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(config.email, EmailConfig::default());
    /// # Ok::<(), cot::Error>(())
    /// ```
    #[cfg(feature = "email")]
    pub email: EmailConfig,
}

const fn default_debug() -> bool {
    cfg!(debug_assertions)
}

impl Default for ProjectConfig {
    fn default() -> Self {
        ProjectConfig::builder().build()
    }
}

impl ProjectConfig {
    /// Create a new [`ProjectConfigBuilder`] to build a [`ProjectConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::ProjectConfig;
    ///
    /// let config = ProjectConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> ProjectConfigBuilder {
        ProjectConfigBuilder::default()
    }

    /// Create a new [`ProjectConfig`] with the default values for development.
    ///
    /// This is useful for development purposes, where you want to have a
    /// configuration that you can just run as quickly as possible. This is
    /// mainly useful for tests and other things that are run in the local
    /// environment.
    ///
    /// Note that what this function returns exactly is not guaranteed to be
    /// the same across different versions of Cot. It's meant to be used as a
    /// starting point for your development configuration and is subject to
    /// change.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::ProjectConfig;
    ///
    /// let config = ProjectConfig::dev_default();
    /// ```
    #[must_use]
    pub fn dev_default() -> ProjectConfig {
        let mut builder = ProjectConfig::builder();
        builder.debug(true).register_panic_hook(true);
        #[cfg(feature = "db")]
        builder.database(DatabaseConfig::builder().url("sqlite::memory:").build());
        builder.build()
    }

    /// Create a new [`ProjectConfig`] from a TOML string.
    ///
    /// # Errors
    ///
    /// This function will return an error if the TOML fails to parse as a
    /// [`ProjectConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::ProjectConfig;
    ///
    /// let toml = r#"
    ///    secret_key = "123abc"
    /// "#;
    /// let config = ProjectConfig::from_toml(toml)?;
    /// # Ok::<_, cot::Error>(())
    /// ```
    pub fn from_toml(toml_content: &str) -> crate::Result<ProjectConfig> {
        let config: ProjectConfig = toml::from_str(toml_content).map_err(ParseConfig)?;
        Ok(config)
    }
}

#[derive(Debug, Error)]
#[error("could not parse the config: {0}")]
struct ParseConfig(#[from] toml::de::Error);
impl_into_cot_error!(ParseConfig);

impl ProjectConfigBuilder {
    /// Builds the project configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::ProjectConfig;
    ///
    /// let config = ProjectConfig::builder().build();
    /// ```
    #[must_use]
    pub fn build(&self) -> ProjectConfig {
        let debug = self.debug.unwrap_or(default_debug());
        ProjectConfig {
            debug,
            register_panic_hook: self.register_panic_hook.unwrap_or(true),
            secret_key: self.secret_key.clone().unwrap_or_default(),
            fallback_secret_keys: self.fallback_secret_keys.clone().unwrap_or_default(),
            auth_backend: self.auth_backend.unwrap_or_default(),
            #[cfg(feature = "db")]
            database: self.database.clone().unwrap_or_default(),
            #[cfg(feature = "cache")]
            cache: self.cache.clone().unwrap_or_default(),
            static_files: self.static_files.clone().unwrap_or_default(),
            middlewares: self.middlewares.clone().unwrap_or_default(),
            #[cfg(feature = "email")]
            email: self.email.clone().unwrap_or_default(),
        }
    }
}

/// The configuration for the authentication backend.
///
/// # Examples
///
/// ```
/// use cot::config::AuthBackendConfig;
///
/// let config = AuthBackendConfig::Database;
/// ```
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuthBackendConfig {
    /// No authentication backend.
    ///
    /// This enables [`NoAuthBackend`](cot::auth::NoAuthBackend) to be used as
    /// the authentication backend, which effectively disables
    /// authentication.
    #[default]
    None,
    /// Database authentication backend.
    ///
    /// This enables [`DatabaseUserBackend`](cot::auth::db::DatabaseUserBackend)
    /// to be used as the authentication backend.
    #[cfg(feature = "db")]
    Database,
}

/// The configuration for the database.
///
/// It is used as part of the [`ProjectConfig`] struct.
///
/// # Examples
///
/// ```
/// use cot::config::DatabaseConfig;
///
/// let config = DatabaseConfig::builder().url("sqlite::memory:").build();
/// ```
#[cfg(feature = "db")]
#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct DatabaseConfig {
    /// The URL of the database, possibly with username, password, and other
    /// options.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{DatabaseConfig, DatabaseUrl};
    ///
    /// let config = DatabaseConfig::builder().url("sqlite::memory:").build();
    /// assert_eq!(config.url, Some(DatabaseUrl::from("sqlite::memory:")));
    /// ```
    #[builder(setter(into, strip_option), default)]
    pub url: Option<DatabaseUrl>,
}

#[cfg(feature = "db")]
impl DatabaseConfigBuilder {
    /// Builds the database configuration.
    ///
    /// # Panics
    ///
    /// This will panic if the database URL is not set.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::DatabaseConfig;
    ///
    /// let config = DatabaseConfig::builder().url("sqlite::memory:").build();
    /// ```
    #[must_use]
    pub fn build(&self) -> DatabaseConfig {
        DatabaseConfig {
            url: self.url.clone().expect("Database URL is required"),
        }
    }
}

#[cfg(feature = "db")]
impl DatabaseConfig {
    /// Create a new [`DatabaseConfigBuilder`] to build a [`DatabaseConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::DatabaseConfig;
    ///
    /// let config = DatabaseConfig::builder().url("sqlite::memory:").build();
    /// ```
    #[must_use]
    pub fn builder() -> DatabaseConfigBuilder {
        DatabaseConfigBuilder::default()
    }
}

/// Expiration policy for cached values.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Timeout {
    /// Never expire the value.
    Never,
    /// Expire after the specified duration from the insertion time.
    After(Duration),
    /// Expire at the specific datetime with a fixed offset.
    AtDateTime(DateTime<FixedOffset>),
}

impl Timeout {
    /// Check if the timeout has expired, given the insertion time (with its
    /// fixed offset).
    ///
    /// # Panics
    ///
    /// This function will panic if the timeout variant is `After` and the
    /// `insertion_time` is `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use chrono::{DateTime, FixedOffset, Utc};
    /// use cot::config::Timeout;
    ///
    /// let timeout = Timeout::After(Duration::from_secs(60));
    /// let insertion_time: DateTime<FixedOffset> =
    ///     Utc::now().with_timezone(&FixedOffset::east_opt(0).unwrap());
    /// assert!(!timeout.is_expired(Some(insertion_time)));
    /// ```
    #[must_use]
    pub fn is_expired(&self, insertion_time: Option<DateTime<FixedOffset>>) -> bool {
        match self {
            Timeout::Never => false,
            Timeout::After(dur) => {
                if let Some(time) = insertion_time {
                    let expiry_time = time + chrono::Duration::from_std(*dur).unwrap_or_default();
                    let now_in_offset = Utc::now().with_timezone(time.offset());
                    return now_in_offset >= expiry_time;
                }
                panic!("insertion_time is required for Timeout::After expiry check");
            }
            Timeout::AtDateTime(dt) => {
                let now_in_offset = Utc::now().with_timezone(dt.offset());
                now_in_offset >= *dt
            }
        }
    }

    /// Convert `After(duration)` into `AtDateTime` anchored at "now" (UTC
    /// offset 0).
    ///
    /// Note: `canonicalize` uses UTC (fixed offset 0) as the produced offset.
    /// If you want to canonicalize with a particular insertion offset,
    /// consider providing that insertion time to the API instead.
    #[must_use]
    #[expect(clippy::missing_panics_doc)]
    pub fn canonicalize(self) -> Self {
        match self {
            Timeout::After(duration) => {
                let time_now = Utc::now().with_timezone(&FixedOffset::east_opt(0).expect("conversion to FixedOffset(0) should not fail since 0 is a valid timezone offset"));
                let expiry_time =
                    time_now + chrono::Duration::from_std(duration).unwrap_or_default();
                Timeout::AtDateTime(expiry_time)
            }
            timeout => timeout,
        }
    }
}

impl Default for Timeout {
    fn default() -> Self {
        // expire after 5 mins.
        Self::After(Duration::from_secs(300))
    }
}

#[cfg(feature = "cache")]
const MAX_RETRIES_DEFAULT: u32 = 3;

#[cfg(feature = "cache")]
#[derive(Debug, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
/// Configuration for the cache system.
///
/// This struct holds all configuration options related to caching, including
/// the cache backend type, connection options, and cache key prefixing.
///
/// # Examples
///
/// ```
/// use cot::config::{CacheConfig, CacheStoreConfig, CacheStoreTypeConfig};
/// let config = CacheConfig::builder()
///     .store(
///         CacheStoreConfig::builder()
///             .store_type(CacheStoreTypeConfig::Memory)
///             .build(),
///     )
///     .build();
/// assert_eq!(config.store.store_type, CacheStoreTypeConfig::Memory);
/// ```
pub struct CacheConfig {
    /// Maximum number of retries for cache operations.
    ///
    /// This controls how many times the cache will attempt to retry failed
    /// operations before giving up. The default is `3` retries.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheConfig;
    ///
    /// let config = CacheConfig::builder().max_retries(5).build();
    /// assert_eq!(config.max_retries, 5);
    /// ```
    ///
    /// # TOML Configuration
    ///
    /// ```toml
    /// [cache]
    /// max_retries = 5
    /// ```
    pub max_retries: u32,

    /// Timeout for cache operations.
    ///
    /// This controls how long to wait for cache operations to complete before
    /// timing out. The default is 300 seconds(5 minutes).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::{CacheConfig, Timeout};
    ///
    /// let config = CacheConfig::builder()
    ///     .timeout(Timeout::After(Duration::from_secs(7200)))
    ///     .build();
    /// assert_eq!(config.timeout, Timeout::After(Duration::from_secs(7200)));
    /// ```
    ///
    /// # TOML Configuration
    ///
    /// ```toml
    /// [cache]
    /// timeout = "2h"
    /// ```
    #[serde(with = "crate::serializers::cache_timeout")]
    pub timeout: Timeout,

    /// Prefix for cache keys.
    ///
    /// This prefix is added to all cache keys.
    /// It's useful for versioning or categorizing cache entries.
    /// When not specified, no prefix is used.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheConfig;
    ///
    /// let config = CacheConfig::builder().prefix("v1".to_string()).build();
    /// assert_eq!(config.prefix, Some("v1".to_string()));
    /// ```
    ///
    /// # TOML Configuration
    ///
    /// ```toml
    /// [cache]
    /// prefix = "v1"
    /// ```
    #[builder(setter(into, strip_option), default)]
    pub prefix: Option<String>,

    /// The cache store configuration.
    ///
    /// This determines which type of cache backend to use (`memory`, `redis`,
    /// `file`) and its specific configuration options.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheConfig, CacheStoreConfig, CacheStoreTypeConfig};
    ///
    /// let config = CacheConfig::builder()
    ///     .store(
    ///         CacheStoreConfig::builder()
    ///             .store_type(CacheStoreTypeConfig::Memory)
    ///             .build(),
    ///     )
    ///     .build();
    ///
    /// assert_eq!(config.store.store_type, CacheStoreTypeConfig::Memory);
    /// ```
    ///
    /// # TOML Configuration
    ///
    /// ```toml
    /// [cache.store]
    /// type = "memory"
    ///
    /// # Or for Redis:
    /// # [cache.store]
    /// # type = "redis"
    /// # url = "redis://localhost:6379"
    /// # pool_size = 20
    ///
    /// # Or for file-based cache:
    /// # [cache.store]
    /// # type = "file"
    /// # path = "/tmp/cache"
    /// ```
    #[builder(default)]
    pub store: CacheStoreConfig,
}

#[cfg(feature = "cache")]
impl CacheConfigBuilder {
    /// Builds the cache configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheConfig, Timeout};
    ///
    /// let config = CacheConfig::builder()
    ///     .max_retries(5)
    ///     .timeout(Timeout::Never)
    ///     .prefix("my-app".to_string())
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(&self) -> CacheConfig {
        CacheConfig {
            max_retries: self.max_retries.unwrap_or(MAX_RETRIES_DEFAULT),
            timeout: self.timeout.unwrap_or_default(),
            prefix: self.prefix.clone().unwrap_or_default(),
            store: self.store.clone().unwrap_or_default(),
        }
    }
}

#[cfg(feature = "cache")]
impl Default for CacheConfig {
    fn default() -> Self {
        CacheConfig::builder().build()
    }
}

#[cfg(feature = "cache")]
impl CacheConfig {
    /// Create a new [`CacheConfigBuilder`] to build a [`CacheConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheConfig;
    /// ```
    #[must_use]
    pub fn builder() -> CacheConfigBuilder {
        CacheConfigBuilder::default()
    }
}

#[cfg(feature = "cache")]
#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
/// Configuration for the cache store backend.
///
/// This struct wraps a [`CacheStoreTypeConfig`] which specifies the actual
/// type of store to use (memory, redis, or file-based).
///
/// # Examples
///
/// ```
/// use cot::config::{CacheStoreConfig, CacheStoreTypeConfig};
/// let config = CacheStoreConfig {
///     store_type: CacheStoreTypeConfig::Memory,
/// };
/// assert_eq!(config.store_type, CacheStoreTypeConfig::Memory);
/// ```
pub struct CacheStoreConfig {
    /// The type of cache store to use.
    ///
    /// This determines how and where cache data is stored. This defaults
    /// to the in-memory store.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheStoreConfig, CacheStoreTypeConfig};
    ///
    /// let config = CacheStoreConfig::builder()
    ///     .store_type(CacheStoreTypeConfig::Memory)
    ///     .build();
    ///
    /// assert_eq!(config.store_type, CacheStoreTypeConfig::Memory);
    /// ```
    #[serde(flatten)]
    pub store_type: CacheStoreTypeConfig,
}

#[cfg(feature = "cache")]
impl CacheStoreConfig {
    /// Create a new [`CacheStoreConfigBuilder`] to build a
    /// [`CacheStoreConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheStoreConfig, CacheStoreTypeConfig};
    ///
    /// let config = CacheStoreConfig::builder()
    ///     .store_type(CacheStoreTypeConfig::Memory)
    ///     .build();
    ///
    /// assert_eq!(config.store_type, CacheStoreTypeConfig::Memory);
    /// ```
    #[must_use]
    pub fn builder() -> CacheStoreConfigBuilder {
        CacheStoreConfigBuilder::default()
    }
}

#[cfg(feature = "cache")]
impl CacheStoreConfigBuilder {
    /// Builds the cache store configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheStoreConfig, CacheStoreTypeConfig};
    ///
    /// let config = CacheStoreConfig::builder()
    ///     .store_type(CacheStoreTypeConfig::Memory)
    ///     .build();
    ///
    /// assert_eq!(config.store_type, CacheStoreTypeConfig::Memory);
    /// ```
    #[must_use]
    pub fn build(&self) -> CacheStoreConfig {
        CacheStoreConfig {
            store_type: self.store_type.clone().unwrap_or_default(),
        }
    }
}

#[cfg(feature = "cache")]
pub(crate) const DEFAULT_REDIS_POOL_SIZE: usize = default_redis_pool_size();

#[cfg(feature = "cache")]
const fn default_redis_pool_size() -> usize {
    10
}

#[expect(clippy::trivially_copy_pass_by_ref)]
#[cfg(feature = "cache")]
const fn is_default_redis_pool_size(size: &usize) -> bool {
    *size == default_redis_pool_size()
}

/// The type of cache store backend to use.
///
/// This specifies which backend is used for caching: `in-memory`, `Redis`,
/// or `file-based`.
///
/// # Examples
///
/// ```
/// use cot::config::CacheStoreTypeConfig;
///
/// let mem = CacheStoreTypeConfig::Memory;
///
/// assert_eq!(mem, CacheStoreTypeConfig::Memory);
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
#[cfg(feature = "cache")]
pub enum CacheStoreTypeConfig {
    /// In-memory cache store.
    ///
    /// This uses a simple in-memory store that does not persist data across
    /// application restarts. This is suitable for development or testing
    /// environments where persistence is not required.
    #[default]
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheStoreTypeConfig;
    ///
    /// let config = CacheStoreTypeConfig::Memory;
    /// ```
    Memory,
    /// Redis cache store.

    /// This stores cache data in a Redis instance. The URL to the Redis server
    /// must be specified, and additional Redis-specific options can be
    /// configured.
    Redis {
        /// # Examples
        ///
        /// ```
        /// use cot::config::{CacheStoreTypeConfig, CacheUrl};
        ///
        /// let config = CacheStoreTypeConfig::Redis {
        ///     url: CacheUrl::from("redis://localhost:6379"),
        ///     pool_size: 20,
        /// };
        /// ```
        /// The URL of the Redis server.
        url: CacheUrl,
        /// Connection pool size for Redis connections.

        /// This controls how many connections to maintain in the connection
        /// pool. When not specified, a default pool size of `10` is used.
        #[serde(
            default = "default_redis_pool_size",
            skip_serializing_if = "is_default_redis_pool_size"
        )]
        pool_size: usize,
    },
    /// File-based cache store.

    /// This stores cache data in files on the local filesystem. The path to
    /// the directory where the cache files will be stored must be specified.
    File {
        /// # Examples
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// use cot::config::CacheStoreTypeConfig;
        ///
        /// let config = CacheStoreTypeConfig::File {
        ///     path: PathBuf::from("/tmp/cache"),
        /// };
        /// ```
        /// The path to the directory where cache files will be stored.
        path: PathBuf,
    },
}

/// The configuration for the static files.
/// The configuration for serving static files.
/// This configuration controls how static files (like CSS, JavaScript, images,
/// etc.) are served by the application. It allows you to customize the URL
/// prefix, caching behavior, and URL rewriting strategy for static assets.
///
/// # Caching
///
/// When the `cache_timeout` is set, the [`Cache-Control`] header is set to
/// `max-age=<cache_timeout>`. This allows browsers to cache the files for the
/// specified duration, improving performance by reducing the number of requests
/// to the server.
///
/// If not set, no caching headers will be sent, and **browsers will need to
/// revalidate the files on each request**.
///
/// The recommended configuration (which is also the default in the project
/// template) is to set the `cache_timeout` to 1 year and use the
/// `QueryParam` rewrite mode. This way, the files are cached for a year, and
/// the URL of the file is rewritten to include a query parameter that changes
/// when the file is updated. This allows for long-lived caching of static
/// files, while invalidating the cache when the file changes.
///
/// [`Cache-Control`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
///
/// # See also
///
/// - ["Love your cache" article on web.dev](https://web.dev/articles/love-your-cache#fingerprinted_urls)
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use cot::config::{StaticFilesConfig, StaticFilesPathRewriteMode};
///
/// let config = StaticFilesConfig::builder()
///     .url("/assets/")
///     .rewrite(StaticFilesPathRewriteMode::QueryParam)
///     .cache_timeout(Duration::from_secs(86400))
///     .build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct StaticFilesConfig {
    /// The URL prefix for the static files to be served at (which should
    /// typically end with a slash). The default is `/static/`.
    ///
    /// This prefix is used to determine which requests should be handled by the
    /// static files middleware. For example, if set to `/assets/`, then
    /// requests to `/assets/style.css` will be served from the static files
    /// directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::StaticFilesConfig;
    ///
    /// let config = StaticFilesConfig::builder().url("/assets/").build();
    /// assert_eq!(config.url, "/assets/");
    /// ```
    #[builder(setter(into))]
    pub url: String,

    /// The URL rewriting mode for the static files. This is useful to allow
    /// long-lived caching of static files, while still allowing to invalidate
    /// the cache when the file changes.
    ///
    /// This affects the URL that is returned by
    /// [`StaticFiles::url_for`](crate::request::extractors::StaticFiles::url_for)
    /// and the actual URL that is used to serve the static files.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{StaticFilesConfig, StaticFilesPathRewriteMode};
    ///
    /// let config = StaticFilesConfig::builder()
    ///     .rewrite(StaticFilesPathRewriteMode::QueryParam)
    ///     .build();
    /// assert_eq!(config.rewrite, StaticFilesPathRewriteMode::QueryParam);
    /// ```
    pub rewrite: StaticFilesPathRewriteMode,

    /// The duration for which static files should be cached by browsers.
    ///
    /// When set, this value is used to set the `Cache-Control` header for
    /// static files. This allows browsers to cache the files for the
    /// specified duration, improving performance by reducing the number of
    /// requests to the server.
    ///
    /// If not set, no caching headers will be sent, and browsers will need to
    /// revalidate the files on each request.
    ///
    /// # TOML
    ///
    /// This field is serialized as a "human-readable" duration, like `4h`,
    /// `1year`, etc. Please refer to the [`humantime::parse_duration`]
    /// documentation for the supported formats for this field.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::StaticFilesConfig;
    ///
    /// let config = StaticFilesConfig::builder()
    ///     .cache_timeout(Duration::from_secs(86400)) // 1 day
    ///     .build();
    /// assert_eq!(config.cache_timeout, Some(Duration::from_secs(86400)));
    /// ```
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::ProjectConfig;
    ///
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [static_files]
    /// cache_timeout = "1h"
    /// "#,
    /// )?;
    ///
    /// assert_eq!(
    ///     config.static_files.cache_timeout,
    ///     Some(Duration::from_secs(3600))
    /// );
    /// # Ok::<(), cot::Error>(())
    /// ```
    #[serde(with = "crate::serializers::humantime")]
    #[builder(setter(strip_option), default)]
    pub cache_timeout: Option<Duration>,
}

/// Configuration for the URL rewriting of static files.
///
/// This is used as part of the [`StaticFilesConfig`] struct.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StaticFilesPathRewriteMode {
    /// No rewriting. The path to the static files is returned as is (with the
    /// URL prefix, if any).
    #[default]
    None,
    /// The path is suffixed with a query parameter `?v=<hash>`, where `<hash>`
    /// is the hash of the file. This is used to allow long-lived caching of
    /// static files, while still serving the files at the same URL (because
    /// providing the query parameter does not change the actual URL). The hash
    /// is used to invalidate the cache when the file changes. This is the
    /// recommended option, along with a long cache timeout (e.g., 1 year).
    QueryParam,
}

impl StaticFilesConfigBuilder {
    /// Builds the static files configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::{StaticFilesConfig, StaticFilesPathRewriteMode};
    ///
    /// let config = StaticFilesConfig::builder()
    ///     .url("/assets/")
    ///     .rewrite(StaticFilesPathRewriteMode::QueryParam)
    ///     .cache_timeout(Duration::from_secs(3600))
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(&self) -> StaticFilesConfig {
        StaticFilesConfig {
            url: self.url.clone().unwrap_or("/static/".to_string()),
            rewrite: self.rewrite.clone().unwrap_or_default(),
            cache_timeout: self.cache_timeout.unwrap_or_default(),
        }
    }
}

impl Default for StaticFilesConfig {
    fn default() -> Self {
        StaticFilesConfig::builder().build()
    }
}

impl StaticFilesConfig {
    /// Create a new [`StaticFilesConfigBuilder`] to build a
    /// [`StaticFilesConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{StaticFilesConfig, StaticFilesPathRewriteMode};
    ///
    /// let config = StaticFilesConfig::builder()
    ///     .rewrite(StaticFilesPathRewriteMode::QueryParam)
    ///     .build();
    /// ```
    #[must_use]
    pub fn builder() -> StaticFilesConfigBuilder {
        StaticFilesConfigBuilder::default()
    }
}

/// The configuration for the middlewares.
///
/// This is used as part of the [`ProjectConfig`] struct.
///
/// # Examples
///
/// ```
/// use cot::config::{LiveReloadMiddlewareConfig, MiddlewareConfig};
///
/// let config = MiddlewareConfig::builder()
///     .live_reload(LiveReloadMiddlewareConfig::builder().enabled(true).build())
///     .build();
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct MiddlewareConfig {
    /// The configuration for the live reload middleware.
    pub live_reload: LiveReloadMiddlewareConfig,
    /// The configuration for the session middleware.
    pub session: SessionMiddlewareConfig,
}

impl MiddlewareConfig {
    /// Create a new [`MiddlewareConfigBuilder`] to build a
    /// [`MiddlewareConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::MiddlewareConfig;
    ///
    /// let config = MiddlewareConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> MiddlewareConfigBuilder {
        MiddlewareConfigBuilder::default()
    }
}

impl MiddlewareConfigBuilder {
    /// Builds the middleware configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{LiveReloadMiddlewareConfig, MiddlewareConfig, SessionMiddlewareConfig};
    ///
    /// let config = MiddlewareConfig::builder()
    ///     .live_reload(LiveReloadMiddlewareConfig::builder().enabled(true).build())
    ///     .session(SessionMiddlewareConfig::builder().secure(false).build())
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(&self) -> MiddlewareConfig {
        MiddlewareConfig {
            live_reload: self.live_reload.clone().unwrap_or_default(),
            session: self.session.clone().unwrap_or_default(),
        }
    }
}

/// The configuration for the live reload middleware.
///
/// This is used as part of the [`MiddlewareConfig`] struct.
///
/// # Examples
///
/// ```
/// use cot::config::LiveReloadMiddlewareConfig;
///
/// let config = LiveReloadMiddlewareConfig::builder().enabled(true).build();
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct LiveReloadMiddlewareConfig {
    /// Whether the live reload middleware is enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::LiveReloadMiddlewareConfig;
    ///
    /// let config = LiveReloadMiddlewareConfig::builder().enabled(true).build();
    /// ```
    pub enabled: bool,
}

impl LiveReloadMiddlewareConfig {
    /// Create a new [`LiveReloadMiddlewareConfigBuilder`] to build a
    /// [`LiveReloadMiddlewareConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::LiveReloadMiddlewareConfig;
    ///
    /// let config = LiveReloadMiddlewareConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> LiveReloadMiddlewareConfigBuilder {
        LiveReloadMiddlewareConfigBuilder::default()
    }
}

impl LiveReloadMiddlewareConfigBuilder {
    /// Builds the live reload middleware configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::LiveReloadMiddlewareConfig;
    ///
    /// let config = LiveReloadMiddlewareConfig::builder().enabled(true).build();
    /// ```
    #[must_use]
    pub fn build(&self) -> LiveReloadMiddlewareConfig {
        LiveReloadMiddlewareConfig {
            enabled: self.enabled.unwrap_or_default(),
        }
    }
}

/// The configuration for the session store type.
///
/// This enum represents the different types of stores that can be used to
/// persist session data. The default is to use an in-memory store, but other
/// options are available like database storage, file-based storage, or
/// cache-based storage.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
///
/// use cot::config::{CacheUrl, SessionStoreTypeConfig};
///
/// // Using in-memory storage (default)
/// let memory_config = SessionStoreTypeConfig::Memory;
///
/// // Using file-based storage
/// let file_config = SessionStoreTypeConfig::File {
///     path: PathBuf::from("/tmp/sessions"),
/// };
///
/// // Using cache-based storage with Redis
/// let cache_config = SessionStoreTypeConfig::Cache {
///     uri: CacheUrl::from("redis://localhost:6379"),
/// };
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum SessionStoreTypeConfig {
    /// In-memory session storage.
    ///
    /// This uses a simple in-memory store that does not persist sessions across
    /// application restarts. This is the default, and is suitable for
    /// development or testing environments.
    #[default]
    Memory,

    /// Database-backed session storage.
    ///
    /// This stores session data in the configured database. This requires the
    /// "db" and "json" features enabled.
    #[cfg(all(feature = "db", feature = "json"))]
    Database,

    /// File-based session storage.
    ///
    /// This stores session data in files on the local filesystem. The path to
    /// the directory where the session files will be stored must be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use cot::config::SessionStoreTypeConfig;
    ///
    /// let config = SessionStoreTypeConfig::File {
    ///     path: PathBuf::from("/tmp/sessions"),
    /// };
    /// ```
    #[cfg(feature = "json")]
    File {
        /// The path to the directory where session files will be stored.
        path: PathBuf,
    },

    /// Cache-based session storage.
    ///
    /// This stores session data in a cache service like Redis. The URI to the
    /// cache service must be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheUrl, SessionStoreTypeConfig};
    ///
    /// let config = SessionStoreTypeConfig::Cache {
    ///     uri: CacheUrl::from("redis://localhost:6379"),
    /// };
    /// ```
    #[cfg(feature = "cache")]
    Cache {
        /// The URI to the cache service.
        uri: CacheUrl,
    },
}

/// The configuration for the session store.
///
/// This is used as part of the [`SessionMiddlewareConfig`] struct and wraps a
/// [`SessionStoreTypeConfig`] which specifies the actual type of store to use.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
///
/// use cot::config::{SessionStoreConfig, SessionStoreTypeConfig};
///
/// let config = SessionStoreConfig::builder()
///     .store_type(SessionStoreTypeConfig::File {
///         path: PathBuf::from("/tmp/sessions"),
///     })
///     .build();
/// ```

#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
pub struct SessionStoreConfig {
    /// The type of session store to use.
    ///
    /// This determines how and where session data is stored. The default is
    /// to use an in-memory store.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheUrl, SessionStoreConfig, SessionStoreTypeConfig};
    ///
    /// let config = SessionStoreConfig::builder()
    ///     .store_type(SessionStoreTypeConfig::Cache {
    ///         uri: CacheUrl::from("redis://localhost:6379"),
    ///     })
    ///     .build();
    /// ```
    #[serde(flatten)]
    pub store_type: SessionStoreTypeConfig,
}

impl SessionStoreConfig {
    /// Create a new [`SessionStoreConfigBuilder`] to build a
    /// [`SessionStoreConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{SessionStoreConfig, SessionStoreTypeConfig};
    ///
    /// let config = SessionStoreConfig::builder()
    ///     .store_type(SessionStoreTypeConfig::Memory)
    ///     .build();
    /// ```
    #[must_use]
    pub fn builder() -> SessionStoreConfigBuilder {
        SessionStoreConfigBuilder::default()
    }
}

impl SessionStoreConfigBuilder {
    /// Builds the session store configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{CacheUrl, SessionStoreConfig, SessionStoreTypeConfig};
    ///
    /// let config = SessionStoreConfig::builder()
    ///     .store_type(SessionStoreTypeConfig::Cache {
    ///         uri: CacheUrl::from("redis://localhost:6379"),
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(&self) -> SessionStoreConfig {
        SessionStoreConfig {
            store_type: self.store_type.clone().unwrap_or_default(),
        }
    }
}

/// The [`SameSite`] attribute of a cookie determines how strictly browsers send
/// cookies on cross-site requests. When not explicitly configured, it defaults
/// to `Strict`, which provides the most restrictive security posture.
///
/// - `Strict`: Cookie is only sent for same-site requests (most restrictive).
/// - `Lax`: Cookie is sent for same-site requests and top-level navigations (a
///   reasonable default).
/// - `None`: Cookie is sent on all requests, including third-party contexts
///   (least restrictive).
///
///  [`SameSite`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#controlling_third-party_cookies_with_samesite
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SameSite {
    /// Only send cookie for same-site requests.
    #[default]
    Strict,

    /// Send cookie on same-site requests and top-level cross-site navigations.
    Lax,

    /// Send cookie on all requests, including third-party.
    None,
}

impl From<SameSite> for tower_sessions::cookie::SameSite {
    fn from(value: SameSite) -> Self {
        match value {
            SameSite::Strict => Self::Strict,
            SameSite::Lax => Self::Lax,
            SameSite::None => Self::None,
        }
    }
}

/// Session expiry configuration.
/// The [`Expiry`] attribute of a cookie determines its lifetime. When not
/// explicitly configured, cookies default to `OnSessionEnd` behavior.
///
/// [`Expiry`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#removal_defining_the_lifetime_of_a_cookie
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use chrono::DateTime;
/// use cot::config::Expiry;
///
/// // Expires when the session ends.
/// let expiry = Expiry::OnSessionEnd;
///
/// // Expires 5 mins after inactivity.
/// let expiry = Expiry::OnInactivity(Duration::from_secs(5 * 60));
///
/// // Expires at the given timestamp.
/// let expired_at =
///     DateTime::parse_from_str("2025-05-27 13:03:00 -0200", "%Y-%m-%d %H:%M:%S %z").unwrap();
/// let expiry = Expiry::AtDateTime(expired_at);
/// ```
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Expiry {
    /// The cookie expires when the browser session ends.
    ///
    /// This is equivalent to not setting the `max-age` or `expires` attributes
    /// in the cookie header, making it a session cookie. The cookie will be
    /// deleted when the user closes their browser or when the browser decides
    /// to end the session.
    ///
    /// This is the most secure option as it ensures sessions don't persist
    /// beyond the browser session, but it may require users to log in more
    /// frequently.
    #[default]
    OnSessionEnd,
    /// The cookie expires after the specified duration of inactivity.
    ///
    /// The session will remain valid as long as the user continues to make
    /// requests within the specified time window. Each request resets the
    /// inactivity timer, extending the session lifetime.
    ///
    /// This provides a balance between security and user convenience, as
    /// active users won't be logged out unexpectedly, but inactive sessions
    /// will eventually expire.
    OnInactivity(Duration),
    /// The cookie expires at the specified date and time.
    ///
    /// The session will remain valid until the exact datetime specified,
    /// regardless of user activity.
    AtDateTime(DateTime<FixedOffset>),
}

impl From<Expiry> for tower_sessions::Expiry {
    fn from(value: Expiry) -> Self {
        match value {
            Expiry::OnSessionEnd => Self::OnSessionEnd,
            Expiry::OnInactivity(duration) => {
                Self::OnInactivity(time::Duration::try_from(duration).unwrap_or_else(|e| {
                    panic!("could not convert {duration:?} into a valid time::Duration: {e:?}",)
                }))
            }
            Expiry::AtDateTime(time) => {
                Self::AtDateTime(DateTimeWithOffsetAdapter::new(time).into_offsetdatetime())
            }
        }
    }
}

/// The configuration for the session middleware.
///
/// This is used as part of the [`MiddlewareConfig`] struct.
///
/// # Examples
///
/// ```
/// use cot::config::SessionMiddlewareConfig;
///
/// let config = SessionMiddlewareConfig::builder().secure(false).build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
#[non_exhaustive]
pub struct SessionMiddlewareConfig {
    /// The [`Secure`] of the cookie determines whether the session middleware
    /// is secure.
    ///
    ///  [`Secure`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies
    /// # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder().secure(false).build();
    /// ```
    pub secure: bool,
    /// The [`HttpOnly`] of the cookie used for the session. It is set to `true`
    /// by default.
    ///
    /// [`HttpOnly`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies
    ///
    ///  # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder().http_only(true).build();
    /// ```
    pub http_only: bool,
    /// The [`SameSite`] attribute of the cookie used for the session.
    /// The default value is [`SameSite::Strict`]
    ///
    /// [`SameSite`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#controlling_third-party_cookies_with_samesite
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{SameSite, SessionMiddlewareConfig};
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .same_site(SameSite::None)
    ///     .build();
    /// ```
    pub same_site: SameSite,

    /// The [`Domain`] attribute of the cookie used for the session. When not
    /// explicitly configured, it is set to `None` by default.
    ///
    /// [`Domain`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#define_where_cookies_are_sent
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .domain("localhost".to_string())
    ///     .build();
    /// ```
    #[builder(setter(strip_option), default)]
    pub domain: Option<String>,
    /// The [`Path`] attribute of the cookie used for the session. It is set to
    /// `/` by default.
    ///
    /// [`Path`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#define_where_cookies_are_sent
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .path(String::from("/random/path"))
    ///     .build();
    /// ```
    pub path: String,
    /// The name of the cookie used for the session. It is set to "id" by
    /// default.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .name("some.id".to_string())
    ///     .build();
    /// ```
    pub name: String,
    /// Whether the unmodified session should be saved on read or not.
    /// If set to `true`, the session will be saved even if it was not modified.
    /// It is set to `false` by default.
    /// # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder().always_save(true).build();
    /// ```
    pub always_save: bool,
    /// The [`Expiry`] behavior for session cookies.
    ///
    /// This controls when the session cookie expires and how long it remains
    /// valid. The expiry behavior affects how the cookie's `max-age` and
    /// `expires` attributes are set in the HTTP response.
    ///
    /// The available expiry modes are:
    /// - `OnSessionEnd`: The cookie expires when the browser session ends. This
    ///   is equivalent to not adding or removing the `max-age`/`expires` field
    ///   in the cookie header, making it a session cookie.
    /// - `OnInactivity`: The cookie expires after the specified duration of
    ///   inactivity. The cookie will be refreshed on each request.
    /// - `AtDateTime`: The cookie expires at the given timestamp, regardless of
    ///   user activity.
    ///
    /// The default value is [`Expiry::OnSessionEnd`] when not specified.
    ///
    /// # TOML
    ///
    /// In TOML configuration, the expiry can be specified in two formats:
    /// - For `OnInactivity`: Use the "humantime" format (e.g., `"1h"`, `"30m"`,
    ///   `"7d"`). Please refer to the [`humantime::parse_duration`]
    ///   documentation for supported formats.
    /// - For `AtDateTime`: Use a valid RFC 3339/ISO 8601 formatted timestamp
    ///   (e.g., `"2025-12-31T23:59:59+00:00"`).
    ///
    /// [`Expiry`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#removal_defining_the_lifetime_of_a_cookie
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use chrono::DateTime;
    /// use cot::config::{Expiry, SessionMiddlewareConfig};
    ///
    /// // Session expires when browser session ends (default)
    /// let config = SessionMiddlewareConfig::builder()
    ///     .expiry(Expiry::OnSessionEnd)
    ///     .build();
    ///
    /// // Session expires after 1 hour of inactivity
    /// let config = SessionMiddlewareConfig::builder()
    ///     .expiry(Expiry::OnInactivity(Duration::from_secs(3600)))
    ///     .build();
    ///
    /// // Session expires at specific datetime
    /// let expire_at =
    ///     DateTime::parse_from_str("2025-12-31 23:59:59 +0000", "%Y-%m-%d %H:%M:%S %z").unwrap();
    /// let config = SessionMiddlewareConfig::builder()
    ///     .expiry(Expiry::AtDateTime(expire_at))
    ///     .build();
    /// ```
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use cot::config::ProjectConfig;
    ///
    /// // TOML configuration for inactivity-based expiry
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [session]
    /// expiry = "2h"
    /// "#,
    /// );
    ///
    /// // TOML configuration for datetime-based expiry
    /// let config = ProjectConfig::from_toml(
    ///     r#"
    /// [session]
    /// expiry = "2025-12-31 23:59:59 +0000"
    /// "#,
    /// );
    /// ```
    #[serde(with = "crate::serializers::session_expiry_time")]
    pub expiry: Expiry,

    /// What session store to use.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{
    ///     CacheUrl, SessionMiddlewareConfig, SessionStoreConfig, SessionStoreTypeConfig,
    /// };
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .store(
    ///         SessionStoreConfig::builder()
    ///             .store_type(SessionStoreTypeConfig::Cache {
    ///                 uri: CacheUrl::from("redis://localhost:6379"),
    ///             })
    ///             .build(),
    ///     )
    ///     .build();
    /// ```
    pub store: SessionStoreConfig,
}

impl SessionMiddlewareConfig {
    /// Create a new [`SessionMiddlewareConfigBuilder`] to build a
    /// [`SessionMiddlewareConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SessionMiddlewareConfig;
    ///
    /// let config = SessionMiddlewareConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> SessionMiddlewareConfigBuilder {
        SessionMiddlewareConfigBuilder::default()
    }
}

impl SessionMiddlewareConfigBuilder {
    /// Builds the session middleware configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{SessionMiddlewareConfig, SessionStoreConfig, SessionStoreTypeConfig};
    ///
    /// let config = SessionMiddlewareConfig::builder()
    ///     .secure(false)
    ///     .store(
    ///         SessionStoreConfig::builder()
    ///             .store_type(SessionStoreTypeConfig::Memory)
    ///             .build(),
    ///     )
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(&self) -> SessionMiddlewareConfig {
        SessionMiddlewareConfig {
            secure: self.secure.unwrap_or(true),
            http_only: self.http_only.unwrap_or(true),
            same_site: self.same_site.unwrap_or_default(),
            domain: self.domain.clone().unwrap_or_default(),
            name: self.name.clone().unwrap_or("id".to_string()),
            path: self.path.clone().unwrap_or(String::from("/")),
            always_save: self.always_save.unwrap_or(false),
            expiry: self.expiry.unwrap_or_default(),
            store: self.store.clone().unwrap_or_default(),
        }
    }
}

impl Default for SessionMiddlewareConfig {
    fn default() -> Self {
        SessionMiddlewareConfig::builder().build()
    }
}

/// The type of email transport backend to use.
///
/// This specifies what email backend is used for sending emails.
/// The default backend if not specified is `console`.
#[cfg(feature = "email")]
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum EmailTransportTypeConfig {
    /// Console email transport backend.
    ///
    /// This is a convenient transport backend for development and testing that
    /// simply prints the email contents to the console instead of actually
    /// sending them.
    #[default]
    Console,
    /// SMTP email transport backend.
    ///
    /// This transport backend sends emails using the Simple Mail Transfer
    /// Protocol (SMTP). It requires authentication details and server
    /// configuration.
    Smtp {
        /// The SMTP connection URL.
        ///
        /// This specifies the protocol, credentials, host, port, and EHLO
        /// domain for connecting to the SMTP server.
        ///
        /// The URL format is:
        /// `scheme://user:password@host:port/?ehlo_domain=domain&tls=TLS`.
        ///
        /// `user` (username) and `password` are optional in the case the
        /// server does not require authentication.
        /// When `port` is not specified, it is automatically determined based
        /// on the `scheme` used.
        /// `tls` is used to specify whether STARTTLS should be used for the
        /// connection. Supported values for `tls` are:
        /// - `required`: Always use STARTTLS. The connection will fail if the
        ///   server does not support it.
        /// - `opportunistic`: Use STARTTLS if the server supports it, otherwise
        ///   fall back to plain connection.
        ///
        /// # Examples
        ///
        /// ```
        /// use cot::config::{EmailTransportTypeConfig, EmailUrl};
        /// use cot::email::transport::smtp::Mechanism;
        ///
        /// let smtp_config = EmailTransportTypeConfig::Smtp {
        ///     url: EmailUrl::from("smtps://johndoe:xxxx xxxxx xxxx xxxxx@smtp.gmail.com"),
        ///     mechanism: Mechanism::Plain,
        /// };
        /// ```
        ///
        /// # TOML Configuration
        ///
        /// ```toml
        /// [email]
        /// type = "smtp"
        /// // If email is "johndoe@gmail.com", then the user is "johndoe"
        /// url = "smtp://johndoe:xxxx xxxx xxxx xxxx@smtp.gmail.com:587?tls=required"
        /// ```
        url: EmailUrl,
        /// The authentication mechanism to use.
        /// Supported mechanisms are `plain`, `login`, and `xoauth2`.
        ///
        /// # TOML Configuration
        ///
        /// ```toml
        /// [email.transport]
        /// type = "smtp"
        /// url = "smtp://johndoe:xxxx xxxx xxxx xxxx@smtp.gmail.com:587?tls=required"
        /// mechanism = "plain" # or "login", "xoauth2"
        /// ```
        mechanism: Mechanism,
    },
}

/// Configuration structure for email transport settings.
///
/// This specifies the email transport backend to use and its associated
/// configuration.
#[cfg(feature = "email")]
#[derive(Debug, Default, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
pub struct EmailTransportConfig {
    /// The type of email transport backend to use.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{EmailTransportConfig, EmailTransportTypeConfig};
    ///
    /// let config = EmailTransportConfig::builder()
    ///     .transport_type(EmailTransportTypeConfig::Console)
    ///     .build();
    /// ```
    #[serde(flatten)]
    pub transport_type: EmailTransportTypeConfig,
}

#[cfg(feature = "email")]
impl EmailTransportConfig {
    /// Create a new [`EmailTransportConfigBuilder`] to build a
    /// [`EmailTransportConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::EmailTransportConfig;
    ///
    /// let config = EmailTransportConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> EmailTransportConfigBuilder {
        EmailTransportConfigBuilder::default()
    }
}

#[cfg(feature = "email")]
impl EmailTransportConfigBuilder {
    /// Builds the email transport configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::EmailTransportConfig;
    ///
    /// let config = EmailTransportConfig::builder().build();
    /// ```
    #[must_use]
    pub fn build(&self) -> EmailTransportConfig {
        EmailTransportConfig {
            transport_type: self.transport_type.clone().unwrap_or_default(),
        }
    }
}

/// Configuration for the email system.
///
/// This specifies all the configuration options for sending emails.
///
/// # Examples
///
/// ```
/// use cot::config::{EmailConfig, EmailTransportConfig, EmailTransportTypeConfig};
///
/// let config = EmailConfig::builder()
///     .transport(
///         EmailTransportConfig::builder()
///             .transport_type(EmailTransportTypeConfig::Console)
///             .build(),
///     )
///     .build();
/// assert_eq!(
///     config.transport.transport_type,
///     EmailTransportTypeConfig::Console
/// );
/// ```
#[cfg(feature = "email")]
#[derive(Debug, Clone, PartialEq, Eq, Builder, Serialize, Deserialize)]
#[builder(build_fn(skip, error = std::convert::Infallible))]
#[serde(default)]
pub struct EmailConfig {
    /// The type of email transport backend to use.
    ///
    /// This determines which type of email transport backend to use (`console`
    /// or `smtp`) along with its configuration options.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::{EmailConfig, EmailTransportConfig, EmailTransportTypeConfig};
    ///
    /// let config = EmailConfig::builder()
    ///     .transport(
    ///         EmailTransportConfig::builder()
    ///             .transport_type(EmailTransportTypeConfig::Console)
    ///             .build(),
    ///     )
    ///     .build();
    /// assert_eq!(
    ///     config.transport.transport_type,
    ///     EmailTransportTypeConfig::Console
    /// );
    /// ```
    ///
    /// # TOML Configuration
    ///
    /// ```toml
    /// [email.transport]
    /// type = "console"
    ///
    /// # Or for SMTP:
    /// # [email.transport]
    /// # type = "smtp"
    /// # auth_id = "your_auth_id"
    /// # secret = "your_secret"
    /// # mechanism = "plain" # or "login", "xoauth2"
    /// # server = "smtp.gmail.com" # or "localhost"
    /// ```
    #[builder(default)]
    pub transport: EmailTransportConfig,
}

#[cfg(feature = "email")]
impl EmailConfig {
    /// Create a new [`EmailConfigBuilder`] to build an
    /// [`EmailConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::EmailConfig;
    ///
    /// let config = EmailConfig::builder().build();
    /// ```
    #[must_use]
    pub fn builder() -> EmailConfigBuilder {
        EmailConfigBuilder::default()
    }
}

#[cfg(feature = "email")]
impl EmailConfigBuilder {
    /// Builds the email configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::EmailConfig;
    ///
    /// let config = EmailConfig::builder().build();
    /// ```
    #[must_use]
    pub fn build(&self) -> EmailConfig {
        EmailConfig {
            transport: self.transport.clone().unwrap_or_default(),
        }
    }
}

#[cfg(feature = "email")]
impl Default for EmailConfig {
    fn default() -> Self {
        EmailConfig::builder().build()
    }
}

/// A secret key.
///
/// This is a wrapper over a byte array, which is used to store a cryptographic
/// key. This is useful for [`ProjectConfig::secret_key`] and
/// [`ProjectConfig::fallback_secret_keys`], which are used to sign cookies and
/// other sensitive data.
///
/// # Security
///
/// The implementation of the [`PartialEq`] trait for this type is constant-time
/// to prevent timing attacks.
///
/// The implementation of the [`Debug`] trait for this type hides the secret key
/// to prevent it from being leaked in logs or other debug output.
///
/// # Examples
///
/// ```
/// use cot::config::SecretKey;
///
/// let key = SecretKey::new(&[1, 2, 3]);
/// assert_eq!(key.as_bytes(), &[1, 2, 3]);
/// ```
#[repr(transparent)]
#[derive(Clone, Serialize, Deserialize)]
#[serde(from = "String")]
pub struct SecretKey(Box<[u8]>);

impl SecretKey {
    /// Create a new [`SecretKey`] from a byte array.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SecretKey;
    ///
    /// let key = SecretKey::new(&[1, 2, 3]);
    /// assert_eq!(key.as_bytes(), &[1, 2, 3]);
    /// ```
    #[must_use]
    pub fn new(hash: &[u8]) -> Self {
        Self(Box::from(hash))
    }

    /// Get the byte array stored in the [`SecretKey`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SecretKey;
    ///
    /// let key = SecretKey::new(&[1, 2, 3]);
    /// assert_eq!(key.as_bytes(), &[1, 2, 3]);
    /// ```
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Consume the [`SecretKey`] and return the byte array stored in it.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::SecretKey;
    ///
    /// let key = SecretKey::new(&[1, 2, 3]);
    /// assert_eq!(key.into_bytes(), Box::from([1, 2, 3]));
    /// ```
    #[must_use]
    pub fn into_bytes(self) -> Box<[u8]> {
        self.0
    }
}

impl From<&[u8]> for SecretKey {
    fn from(value: &[u8]) -> Self {
        Self::new(value)
    }
}

impl From<String> for SecretKey {
    fn from(value: String) -> Self {
        Self::new(value.as_bytes())
    }
}

impl From<&str> for SecretKey {
    fn from(value: &str) -> Self {
        Self::new(value.as_bytes())
    }
}

impl PartialEq for SecretKey {
    fn eq(&self, other: &Self) -> bool {
        self.0.ct_eq(&other.0).into()
    }
}

impl Eq for SecretKey {}

impl Debug for SecretKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // write in single line, regardless whether alternate mode was used or not
        write!(f, "SecretKey(\"**********\")")
    }
}

impl Default for SecretKey {
    fn default() -> Self {
        Self::new(&[])
    }
}

/// A URL for the database.
///
/// This is a wrapper over the [`url::Url`] type, which is used to store the
/// URL of the database. It parses the URL and ensures that it is valid.
///
/// # Security
///
/// The implementation of the [`Debug`] trait for this type hides the password
/// from the debug output.
///
/// # Examples
///
/// ```
/// use cot::config::DatabaseUrl;
///
/// let url = DatabaseUrl::from("postgres://user:password@localhost:5432/database");
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg(feature = "db")]
pub struct DatabaseUrl(url::Url);

#[cfg(feature = "db")]
impl DatabaseUrl {
    /// Returns the string representation of the database URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::DatabaseUrl;
    ///
    /// let url = DatabaseUrl::from("postgres://user:password@localhost:5432/database");
    /// assert_eq!(
    ///     url.as_str(),
    ///     "postgres://user:password@localhost:5432/database"
    /// );
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

#[cfg(feature = "db")]
impl From<String> for DatabaseUrl {
    fn from(url: String) -> Self {
        Self(url::Url::parse(&url).expect("valid URL"))
    }
}

#[cfg(feature = "db")]
impl From<&str> for DatabaseUrl {
    fn from(url: &str) -> Self {
        Self(url::Url::parse(url).expect("valid URL"))
    }
}

#[cfg(feature = "db")]
impl Debug for DatabaseUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let new_url = conceal_url_parts(&self.0);

        f.debug_tuple("DatabaseUrl")
            .field(&new_url.as_str())
            .finish()
    }
}

/// An error returned when parsing a `CacheType` from a string.
#[derive(Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseCacheTypeError {
    /// The input did not match any supported cache type.
    #[error("unsupported cache type: `{0}`")]
    Unsupported(String),
}

/// A structure that holds the type of Cache.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg(feature = "cache")]
#[non_exhaustive]
pub enum CacheType {
    /// A redis cache type.
    #[cfg(feature = "redis")]
    Redis,
}

#[cfg(feature = "cache")]
impl TryFrom<&str> for CacheType {
    type Error = ParseCacheTypeError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            #[cfg(feature = "redis")]
            "redis" => Ok(CacheType::Redis),
            other => Err(ParseCacheTypeError::Unsupported(other.to_owned())),
        }
    }
}

#[cfg(feature = "cache")]
impl std::str::FromStr for CacheType {
    type Err = ParseCacheTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        CacheType::try_from(s)
    }
}

/// A URL for caches.
///
/// This is a wrapper over the [`url::Url`] type, which is used to store the
/// URL of a cache. It parses the URL and ensures that it is valid.
///
/// # Security
///
/// The implementation of the [`Debug`] trait for this type hides the password
/// from the debug output.
///
/// # Examples
///
/// ```
/// use cot::config::CacheUrl;
///
/// let url = CacheUrl::from("redis://user:password@localhost:6379/0");
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg(feature = "cache")]
pub struct CacheUrl(url::Url);

#[cfg(feature = "cache")]
impl CacheUrl {
    /// Returns the string representation of the cache URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheUrl;
    ///
    /// let url = CacheUrl::from("redis://user:password@localhost:6379/0");
    /// assert_eq!(url.as_str(), "redis://user:password@localhost:6379/0");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Returns the scheme of the cache URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::CacheUrl;
    ///
    /// let url = CacheUrl::from("redis://user:password@localhost:6379/0");
    /// assert_eq!(url.scheme(), "redis");
    /// ```
    #[must_use]
    pub fn scheme(&self) -> &str {
        self.0.scheme()
    }

    #[allow(clippy::allow_attributes, unused, reason = "used in tests")]
    pub(crate) fn inner_mut(&mut self) -> &mut url::Url {
        &mut self.0
    }
}

#[cfg(feature = "cache")]
impl From<String> for CacheUrl {
    fn from(url: String) -> Self {
        Self(url::Url::parse(&url).expect("invalid  cache URL"))
    }
}

#[cfg(feature = "cache")]
impl From<&str> for CacheUrl {
    fn from(url: &str) -> Self {
        Self(url::Url::parse(url).expect("invalid cache URL"))
    }
}

#[cfg(feature = "cache")]
impl TryFrom<CacheUrl> for CacheType {
    type Error = ParseCacheTypeError;

    fn try_from(value: CacheUrl) -> Result<Self, Self::Error> {
        CacheType::try_from(value.0.scheme())
    }
}

#[cfg(feature = "cache")]
impl Debug for CacheUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let new_url = conceal_url_parts(&self.0);

        f.debug_tuple("CacheUrl").field(&new_url.as_str()).finish()
    }
}

#[cfg(any(feature = "cache", feature = "db"))]
fn conceal_url_parts(url: &url::Url) -> url::Url {
    let mut new_url = url.clone();
    if !new_url.username().is_empty() {
        new_url
            .set_username("********")
            .expect("set_username should succeed if username is present");
    }
    if new_url.password().is_some() {
        new_url
            .set_password(Some("********"))
            .expect("set_password should succeed if password is present");
    }
    new_url
}

#[cfg(feature = "cache")]
impl std::fmt::Display for CacheUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0.as_str())
    }
}

/// A URL for email services.
///
/// This is a wrapper over the [`url::Url`] type, which is used to store the
/// URL of an email service. It parses the URL and ensures that it is valid.
///
/// # Examples
///
/// ```
/// use cot::config::EmailUrl;
/// let url = EmailUrl::from("smtp://user:pass@hostname:587");
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg(feature = "email")]
pub struct EmailUrl(url::Url);

#[cfg(feature = "email")]
impl EmailUrl {
    /// Returns the string representation of the email URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::config::EmailUrl;
    ///
    /// let url = EmailUrl::from("smtp://user:pass@hostname:587");
    /// assert_eq!(url.as_str(), "smtp://user:pass@hostname:587");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

#[cfg(feature = "email")]
impl From<String> for EmailUrl {
    fn from(url: String) -> Self {
        Self(url::Url::parse(&url).expect("valid URL"))
    }
}

#[cfg(feature = "email")]
impl From<&str> for EmailUrl {
    fn from(url: &str) -> Self {
        Self(url::Url::parse(url).expect("valid URL"))
    }
}

#[cfg(test)]
mod tests {
    use time::OffsetDateTime;

    use super::*;

    #[test]
    fn from_toml_valid() {
        let toml_content = r#"
            debug = true
            register_panic_hook = true
            secret_key = "123abc"
            fallback_secret_keys = ["456def", "789ghi"]
            auth_backend = { type = "none" }

            [static_files]
            url = "/assets/"
            rewrite = "none"
            cache_timeout = "1h"

            [middlewares]
            live_reload.enabled = true
            [middlewares.session]
            secure = false
            http_only = false
            domain = "localhost"
            path = "/some/path"
            always_save = true
            name = "some.sid"
        "#;

        let config = ProjectConfig::from_toml(toml_content).unwrap();

        assert!(config.debug);
        assert!(config.register_panic_hook);
        assert_eq!(config.secret_key.as_bytes(), b"123abc");
        assert_eq!(config.fallback_secret_keys.len(), 2);
        assert_eq!(config.fallback_secret_keys[0].as_bytes(), b"456def");
        assert_eq!(config.fallback_secret_keys[1].as_bytes(), b"789ghi");
        assert_eq!(config.auth_backend, AuthBackendConfig::None);
        assert_eq!(config.static_files.url, "/assets/");
        assert_eq!(
            config.static_files.rewrite,
            StaticFilesPathRewriteMode::None
        );
        assert_eq!(
            config.static_files.cache_timeout,
            Some(Duration::from_secs(3600))
        );
        assert!(config.middlewares.live_reload.enabled);
        assert!(!config.middlewares.session.secure);
        assert!(!config.middlewares.session.http_only);
        assert_eq!(
            config.middlewares.session.domain,
            Some(String::from("localhost"))
        );
        assert!(config.middlewares.session.always_save);
        assert_eq!(config.middlewares.session.name, String::from("some.sid"));
        assert_eq!(config.middlewares.session.path, String::from("/some/path"));
    }

    #[test]
    fn default_values_from_valid_toml() {
        let toml_content = "";

        let config = ProjectConfig::from_toml(toml_content).unwrap();
        assert!(config.debug);
        assert!(config.register_panic_hook);
        assert_eq!(config.secret_key.as_bytes(), b"");
        assert_eq!(config.fallback_secret_keys.len(), 0);
        assert_eq!(config.auth_backend, AuthBackendConfig::None);
        assert_eq!(config.static_files.url, "/static/");
        assert_eq!(
            config.static_files.rewrite,
            StaticFilesPathRewriteMode::None
        );
        assert_eq!(config.static_files.cache_timeout, None);
        assert!(!config.middlewares.live_reload.enabled);
        assert!(config.middlewares.session.secure);
        assert!(config.middlewares.session.http_only);
        assert_eq!(config.middlewares.session.domain, None);
        assert!(!config.middlewares.session.always_save);
        assert_eq!(config.middlewares.session.name, String::from("id"));
        assert_eq!(config.middlewares.session.path, String::from("/"));
        assert_eq!(config.middlewares.session.same_site, SameSite::Strict);
        assert_eq!(config.middlewares.session.expiry, Expiry::OnSessionEnd);
        assert_eq!(
            config.middlewares.session.store.store_type,
            SessionStoreTypeConfig::Memory
        );
        assert_eq!(config.database.url, None);
    }

    #[test]
    fn same_site_from_valid_toml() {
        let same_site_options = [
            (
                "none",
                SameSite::None,
                tower_sessions::cookie::SameSite::None,
            ),
            ("lax", SameSite::Lax, tower_sessions::cookie::SameSite::Lax),
            (
                "strict",
                SameSite::Strict,
                tower_sessions::cookie::SameSite::Strict,
            ),
        ];
        for (value, expected, tower_sessions_expected) in same_site_options {
            let toml_content = format!(
                r#"
            [middlewares.session]
            same_site = "{value}"
        "#
            );
            let config = ProjectConfig::from_toml(&toml_content).unwrap();
            let actual = config.middlewares.session.same_site;
            assert_eq!(actual, expected);
            assert_eq!(
                tower_sessions::cookie::SameSite::from(actual),
                tower_sessions_expected
            );
        }
    }

    #[test]
    fn expiry_from_valid_toml() {
        let expiry_opts = [
            (
                "2h",
                Expiry::OnInactivity(Duration::from_secs(7200)),
                tower_sessions::Expiry::OnInactivity(time::Duration::seconds(7200)),
            ),
            (
                "2025-12-31T23:59:59+00:00",
                Expiry::AtDateTime(
                    DateTime::parse_from_rfc3339("2025-12-31T23:59:59+00:00").unwrap(),
                ),
                tower_sessions::Expiry::AtDateTime(OffsetDateTime::new_utc(
                    time::Date::from_calendar_date(2025, time::Month::December, 31).unwrap(),
                    time::Time::from_hms(23, 59, 59).unwrap(),
                )),
            ),
        ];
        for (value, expected, tower_session_expected) in expiry_opts {
            let toml_content = format!(
                r#"
            [middlewares.session]
            expiry = "{value}"
        "#
            );
            let config = ProjectConfig::from_toml(&toml_content).unwrap();
            let actual = config.middlewares.session.expiry;
            assert_eq!(actual, expected);
            assert_eq!(tower_sessions::Expiry::from(actual), tower_session_expected);
        }
    }

    #[test]
    fn expiry_from_invalid_toml() {
        let toml_content = r#"
            [middlewares.session]
            expiry = "invalid time"
        "#
        .to_string();

        let config = ProjectConfig::from_toml(&toml_content);
        assert!(config.is_err());
        assert!(
            config
                .unwrap_err()
                .to_string()
                .contains("could not parse the config")
        );
    }

    #[test]
    fn session_store_valid_toml() {
        let toml_content = r#"
            debug = true
            register_panic_hook = true
            secret_key = "123abc"
            fallback_secret_keys = ["456def", "789ghi"]
            auth_backend = { type = "none" }

            [static_files]
            url = "/assets/"
            rewrite = "none"
            cache_timeout = "1h"

            [middlewares]
            live_reload.enabled = true
            [middlewares.session]
            secure = false
        "#;

        let store_configs = [
            (
                r#"
            [middlewares.session.store]
            type = "memory"
            "#,
                SessionStoreTypeConfig::Memory,
            ),
            #[cfg(feature = "cache")]
            (
                r#"
            [middlewares.session.store]
            type = "cache"
            uri = "redis://redis"
            "#,
                SessionStoreTypeConfig::Cache {
                    uri: CacheUrl::from("redis://redis"),
                },
            ),
            (
                r#"
            [middlewares.session.store]
            type = "file"
            path = "session/path/"
            "#,
                SessionStoreTypeConfig::File {
                    path: PathBuf::from("session/path"),
                },
            ),
            #[cfg(all(feature = "db", feature = "json"))]
            (
                r#"
            [middlewares.session.store]
            type = "database"
            "#,
                SessionStoreTypeConfig::Database,
            ),
        ];

        for (cfg_toml, cfg_type) in store_configs {
            let full_cfg_str = format!("{toml_content}\n{cfg_toml}");
            let config = ProjectConfig::from_toml(&full_cfg_str).unwrap();
            assert_eq!(config.middlewares.session.store.store_type, cfg_type);
        }
    }
    #[test]
    fn from_toml_invalid() {
        let toml_content = r"
            debug = true
            secret_key = 123abc
        ";

        let result = ProjectConfig::from_toml(toml_content);
        assert!(result.is_err());
    }

    #[test]
    fn from_toml_missing_fields() {
        let toml_content = r#"
            secret_key = "123abc"

            [static_files]
            rewrite = "query_param"
        "#;

        let config = ProjectConfig::from_toml(toml_content).unwrap();
        assert_eq!(config.debug, cfg!(debug_assertions));
        assert_eq!(config.secret_key.as_bytes(), b"123abc");

        assert_eq!(config.static_files.url, "/static/");
        assert_eq!(
            config.static_files.rewrite,
            StaticFilesPathRewriteMode::QueryParam
        );
    }
    #[test]
    #[cfg(feature = "redis")]
    fn cache_type_from_str_redis() {
        assert_eq!(CacheType::try_from("redis").unwrap(), CacheType::Redis);
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_type_from_str_unknown() {
        for &s in &["", "foo", "redis://foo"] {
            assert_eq!(
                CacheType::try_from(s),
                Err(ParseCacheTypeError::Unsupported(s.to_owned()))
            );
        }
    }

    #[test]
    #[cfg(feature = "redis")]
    fn cache_type_from_cacheurl() {
        let url = CacheUrl::from("redis://localhost/");
        assert_eq!(CacheType::try_from(url.clone()).unwrap(), CacheType::Redis);

        let other = CacheUrl::from("http://example.com/");
        assert_eq!(
            CacheType::try_from(other),
            Err(ParseCacheTypeError::Unsupported("http".to_string()))
        );
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cacheurl_from_str_and_string() {
        let s = "http://example.com/foo";
        let u1 = CacheUrl::from(s);
        let u2 = CacheUrl::from(s.to_string());
        assert_eq!(u1, u2);
        assert_eq!(u1.as_str(), s);
    }

    #[test]
    #[cfg(feature = "cache")]
    #[should_panic(expected = "invalid cache URL")]
    fn cacheurl_from_invalid_str_panics() {
        let _ = CacheUrl::from("not a url");
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cacheurl_as_str_roundtrip() {
        let raw = "https://user:pass@host:1234/path?query#frag";
        let cu = CacheUrl::from(raw);
        assert_eq!(cu.as_str(), url::Url::parse(raw).unwrap().as_str());
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cacheurl_debug_masks_credentials() {
        let raw = "https://user:secret@host:1234/path";
        let cu = CacheUrl::from(raw);
        let dbg = format!("{cu:?}");
        assert!(dbg.starts_with("CacheUrl(\"https://********:********@host:1234/path\")"));
    }

    #[test]
    fn conceal_url_details_leaves_no_credentials() {
        let raw = "ftp://alice:alicepwd@server/";
        let parsed = url::Url::parse(raw).unwrap();
        let concealed = conceal_url_parts(&parsed);
        assert_eq!(concealed.username(), "********");
        assert_eq!(concealed.password(), Some("********"));
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_from_toml_memory() {
        let toml_content = r#"
            [cache]
            max_retries = 5
            timeout = "60s"
            prefix = "v1"

            [cache.store]
            type = "memory"
        "#;

        let config = ProjectConfig::from_toml(toml_content).unwrap();

        assert_eq!(config.cache.max_retries, 5);
        assert_eq!(
            config.cache.timeout,
            Timeout::After(Duration::from_secs(60))
        );
        assert_eq!(config.cache.prefix, Some("v1".to_string()));
        assert_eq!(config.cache.store.store_type, CacheStoreTypeConfig::Memory);
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_from_toml_redis() {
        macro_rules! cache_toml_with_pool {
            () => {
                r#"
                [cache]
                max_retries = 10
                timeout = "120s"

                [cache.store]
                type = "redis"
                url = "redis://localhost:6379"
                pool_size = 20
                "#
            };
        }

        macro_rules! cache_toml_without_pool {
            () => {
                r#"
                [cache]
                max_retries = 10
                timeout = "120s"

                [cache.store]
                type = "redis"
                url = "redis://localhost:6379"
                "#
            };
        }

        let variants: [(&str, usize); 2] = [
            (cache_toml_with_pool!(), 20),
            (cache_toml_without_pool!(), default_redis_pool_size()),
        ];

        for (toml_content, expected_size) in variants {
            let config = ProjectConfig::from_toml(toml_content).unwrap();

            assert_eq!(config.cache.max_retries, 10);
            assert_eq!(
                config.cache.timeout,
                Timeout::After(Duration::from_secs(120))
            );
            assert_eq!(config.cache.prefix, None);

            if let CacheStoreTypeConfig::Redis { url, pool_size } = config.cache.store.store_type {
                assert_eq!(url.as_str(), "redis://localhost:6379");
                assert_eq!(pool_size, expected_size);
            }
        }
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_from_toml_file() {
        let toml_content = r#"
            [cache]
            max_retries = 3
            timeout = "30s"
            prefix = "dev"

            [cache.store]
            type = "file"
            path = "/tmp/cache"
        "#;

        let config = ProjectConfig::from_toml(toml_content).unwrap();

        assert_eq!(config.cache.max_retries, 3);
        assert_eq!(
            config.cache.timeout,
            Timeout::After(Duration::from_secs(30))
        );
        assert_eq!(config.cache.prefix, Some("dev".to_string()));

        if let CacheStoreTypeConfig::File { path } = &config.cache.store.store_type {
            assert_eq!(path, &PathBuf::from("/tmp/cache"));
        }
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_defaults() {
        let toml_content = r"
            [cache]
        ";

        let config = ProjectConfig::from_toml(toml_content).unwrap();
        assert_eq!(config.cache.max_retries, 3);
        assert_eq!(config.cache.timeout, Timeout::default());
        assert_eq!(config.cache.prefix, None);
        assert_eq!(config.cache.store.store_type, CacheStoreTypeConfig::Memory);
    }

    #[test]
    #[cfg(feature = "cache")]
    fn test_is_default_redis_pool_size() {
        assert!(is_default_redis_pool_size(&10));
    }
    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_builder() {
        let config = CacheConfig::builder()
            .max_retries(7)
            .timeout(Timeout::After(Duration::from_secs(90)))
            .prefix("v2".to_string())
            .store(CacheStoreConfig {
                store_type: CacheStoreTypeConfig::Memory,
            })
            .build();

        assert_eq!(config.max_retries, 7);
        assert_eq!(config.timeout, Timeout::After(Duration::from_secs(90)));
        assert_eq!(config.prefix, Some("v2".to_string()));
        assert_eq!(config.store.store_type, CacheStoreTypeConfig::Memory);
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_config_builder_defaults() {
        let config = CacheConfig::builder().build();

        assert_eq!(config.max_retries, 3);
        assert_eq!(config.timeout, Timeout::default());
        assert_eq!(config.prefix, None);
        assert_eq!(config.store.store_type, CacheStoreTypeConfig::Memory);
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_store_config_builder() {
        let config = CacheStoreConfig {
            store_type: CacheStoreTypeConfig::Redis {
                url: CacheUrl::from("redis://localhost:6379"),
                pool_size: 15,
            },
        };

        if let CacheStoreTypeConfig::Redis { url, pool_size } = config.store_type {
            assert_eq!(url.as_str(), "redis://localhost:6379");
            assert_eq!(pool_size, 15);
        }
    }

    #[test]
    #[cfg(feature = "cache")]
    fn cache_store_config_default() {
        let config = CacheStoreConfig::default();
        assert_eq!(config.store_type, CacheStoreTypeConfig::Memory);
    }
    #[test]
    fn never_is_never_expired() {
        let now_fixed: DateTime<FixedOffset> =
            Utc::now().with_timezone(&FixedOffset::east_opt(0).unwrap());
        assert!(!Timeout::Never.is_expired(Some(now_fixed)));
        assert!(!Timeout::Never.is_expired(None));
    }

    #[test]
    fn after_is_expired_based_on_insertion_offset() {
        // insertion_time is 1 hour in the past with +1h offset
        let offset = FixedOffset::east_opt(3600).unwrap();
        let insertion_time: DateTime<FixedOffset> =
            (Utc::now() - chrono::Duration::hours(1)).with_timezone(&offset);
        let timeout = Timeout::After(Duration::from_secs(60)); // 1 minute
        assert!(timeout.is_expired(Some(insertion_time)));
    }

    #[test]
    fn after_is_not_expired_when_not_yet_passed_with_offset() {
        // insertion_time 10s ago with -2h offset
        let offset = FixedOffset::east_opt(-2 * 3600).unwrap();
        let insertion_time: DateTime<FixedOffset> =
            (Utc::now() - chrono::Duration::seconds(10)).with_timezone(&offset);
        let timeout = Timeout::After(Duration::from_secs(60));
        assert!(!timeout.is_expired(Some(insertion_time)));
    }

    #[test]
    #[should_panic(expected = "insertion_time is required for Timeout::After expiry check")]
    fn after_is_expired_panics_with_no_insertion_time() {
        let timeout = Timeout::After(Duration::from_secs(60));
        let _ = timeout.is_expired(None);
    }

    #[test]
    fn atdatetime_respects_stored_offset_when_comparing() {
        // Build a past and future instant and attach +1h offset
        let offset = FixedOffset::east_opt(3600).unwrap();
        let past: DateTime<FixedOffset> =
            (Utc::now() - chrono::Duration::seconds(60)).with_timezone(&offset);
        let future: DateTime<FixedOffset> =
            (Utc::now() + chrono::Duration::seconds(60)).with_timezone(&offset);

        assert!(Timeout::AtDateTime(past).is_expired(None));
        assert!(!Timeout::AtDateTime(future).is_expired(None));
    }

    #[test]
    fn canonicalize_after_produces_atdatetime_in_utc_offset_zero() {
        let before = Utc::now().with_timezone(&FixedOffset::east_opt(0).unwrap());
        let duration = Duration::from_secs(2);
        let canon = Timeout::After(duration).canonicalize();

        match canon {
            Timeout::AtDateTime(dt) => {
                // dt offset should be UTC (0)
                assert_eq!(dt.offset().local_minus_utc(), 0);
                // dt should be >= before
                assert!(dt >= before);
                // dt should be reasonably close to before + duration (allow 1s slack)
                let max_allowed = before
                    + chrono::Duration::from_std(duration).unwrap()
                    + chrono::Duration::seconds(1);
                assert!(
                    dt <= max_allowed,
                    "canonicalized datetime is unexpectedly far ahead"
                );
            }
            other => panic!("expected AtDateTime, got {other:?}"),
        }
    }

    #[test]
    fn canonicalize_preserves_atdatetime_and_never() {
        let dt: DateTime<FixedOffset> = (Utc::now() + chrono::Duration::seconds(10))
            .with_timezone(&FixedOffset::east_opt(0).unwrap());
        let t = Timeout::AtDateTime(dt);
        assert_eq!(t.canonicalize(), t);

        let never = Timeout::Never;
        assert_eq!(never.canonicalize(), Timeout::Never);
    }

    #[test]
    #[cfg(feature = "email")]
    fn email_config_from_toml_console() {
        let toml_content = r#"
            [email]
            type = "console"
        "#;

        let config = ProjectConfig::from_toml(toml_content).unwrap();

        assert_eq!(
            config.email.transport.transport_type,
            EmailTransportTypeConfig::Console
        );
    }

    #[test]
    #[cfg(feature = "email")]
    fn email_config_from_toml_smtp() {
        let toml_content = r#"
            [email.transport]
            type = "smtp"
            url = "smtp://user:pass@hostname:587"
            mechanism = "plain"
        "#;
        let config = ProjectConfig::from_toml(toml_content).unwrap();

        if let EmailTransportTypeConfig::Smtp { url, mechanism } =
            &config.email.transport.transport_type
        {
            assert_eq!(url.as_str(), "smtp://user:pass@hostname:587");
            assert_eq!(*mechanism, Mechanism::Plain);
        }
    }

    #[test]
    #[cfg(feature = "email")]
    fn email_config_builder_defaults() {
        let config = EmailConfig::builder().build();
        assert_eq!(
            config.transport.transport_type,
            EmailTransportTypeConfig::Console
        );
    }

    #[test]
    #[cfg(feature = "email")]
    fn email_url_from_str_and_string() {
        let s = "smtp://user:pass@hostname:587";
        let u1 = EmailUrl::from(s);
        let u2 = EmailUrl::from(s.to_string());
        assert_eq!(u1, u2);
        assert_eq!(u1.as_str(), s);
    }
}