gatehouse 0.2.0

A flexible authorization library that combines role-based (RBAC), attribute-based (ABAC), and relationship-based (ReBAC) access control policies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
//! A flexible authorization library that combines role‐based (RBAC),
//! attribute‐based (ABAC), and relationship‐based (ReBAC) policies.
//! The library provides a generic `Policy` trait for defining custom policies,
//! a builder pattern for creating custom policies as well as several built-in
//! policies for common use cases, and combinators for composing complex
//! authorization logic.
//!
//! # Overview
//!
//! A *Policy* is an asynchronous decision unit that checks if a given subject may
//! perform an action on a resource within a given context. Policies implement the
//! [`Policy`] trait. A [`PermissionChecker`] aggregates multiple policies and uses OR
//! logic by default (i.e. if any policy grants access, then access is allowed).
//! The [`PolicyBuilder`] offers a builder pattern for creating custom policies.
//!
//! ## Quick Start
//!
//! The fastest way to define a policy is with [`PolicyBuilder`]:
//!
//! ```rust
//! # use gatehouse::*;
//! #[derive(Debug, Clone)]
//! struct User { roles: Vec<String> }
//! #[derive(Debug, Clone)]
//! struct Document;
//! #[derive(Debug, Clone)]
//! struct ReadAction;
//! #[derive(Debug, Clone)]
//! struct AppContext;
//!
//! let policy = PolicyBuilder::<User, Document, ReadAction, AppContext>::new("AdminOnly")
//!     .subjects(|user: &User| user.roles.iter().any(|r| r == "admin"))
//!     .build();
//!
//! let mut checker = PermissionChecker::new();
//! checker.add_policy(policy);
//!
//! # tokio_test::block_on(async {
//! let admin = User { roles: vec!["admin".into()] };
//! assert!(checker.evaluate_access(&admin, &ReadAction, &Document, &AppContext).await.is_granted());
//!
//! let guest = User { roles: vec!["guest".into()] };
//! assert!(!checker.evaluate_access(&guest, &ReadAction, &Document, &AppContext).await.is_granted());
//! # });
//! ```
//!
//! ## Built-in Policies
//!
//! The library provides several built-in policies:
//!  - [`RbacPolicy`]: A role-based access control policy.
//!  - [`AbacPolicy`]: An attribute-based access control policy.
//!  - [`RebacPolicy`]: A relationship-based access control policy.
//!
//! ## Custom Policies
//!
//! For full control, implement the [`Policy`] trait directly. Below we define a simple
//! system where a user may read a document if they are an admin (via a role-based policy)
//! or if they are the owner of the document (via an attribute-based policy).
//!
//! ```rust
//! # use uuid::Uuid;
//! # use async_trait::async_trait;
//! # use std::sync::Arc;
//! # use gatehouse::*;
//!
//! // Define our core types.
//! #[derive(Debug, Clone)]
//! pub struct User {
//!     pub id: Uuid,
//!     pub roles: Vec<String>,
//! }
//!
//! #[derive(Debug, Clone)]
//! pub struct Document {
//!     pub id: Uuid,
//!     pub owner_id: Uuid,
//! }
//!
//! #[derive(Debug, Clone)]
//! pub struct ReadAction;
//!
//! #[derive(Debug, Clone)]
//! pub struct EmptyContext;
//!
//! // A simple RBAC policy: grant access if the user has the "admin" role.
//! struct AdminPolicy;
//! #[async_trait]
//! impl Policy<User, Document, ReadAction, EmptyContext> for AdminPolicy {
//!     async fn evaluate_access(
//!         &self,
//!         user: &User,
//!         _action: &ReadAction,
//!         _resource: &Document,
//!         _context: &EmptyContext,
//!     ) -> PolicyEvalResult {
//!         if user.roles.contains(&"admin".to_string()) {
//!             PolicyEvalResult::Granted {
//!                 policy_type: self.policy_type(),
//!                 reason: Some("User is admin".to_string()),
//!             }
//!         } else {
//!             PolicyEvalResult::Denied {
//!                 policy_type: self.policy_type(),
//!                 reason: "User is not admin".to_string(),
//!             }
//!         }
//!     }
//!     fn policy_type(&self) -> String { "AdminPolicy".to_string() }
//! }
//!
//! // An ABAC policy: grant access if the user is the owner of the document.
//! struct OwnerPolicy;
//!
//! #[async_trait]
//! impl Policy<User, Document, ReadAction, EmptyContext> for OwnerPolicy {
//!     async fn evaluate_access(
//!         &self,
//!         user: &User,
//!         _action: &ReadAction,
//!         document: &Document,
//!         _context: &EmptyContext,
//!     ) -> PolicyEvalResult {
//!         if user.id == document.owner_id {
//!             PolicyEvalResult::Granted {
//!                 policy_type: self.policy_type(),
//!                 reason: Some("User is the owner".to_string()),
//!             }
//!         } else {
//!             PolicyEvalResult::Denied {
//!                policy_type: self.policy_type(),
//!                reason: "User is not the owner".to_string(),
//!            }
//!         }
//!     }
//!     fn policy_type(&self) -> String {
//!         "OwnerPolicy".to_string()
//!     }
//! }
//!
//! // Create a PermissionChecker (which uses OR semantics by default) and add both policies.
//! fn create_document_checker() -> PermissionChecker<User, Document, ReadAction, EmptyContext> {
//!     let mut checker = PermissionChecker::new();
//!     checker.add_policy(AdminPolicy);
//!     checker.add_policy(OwnerPolicy);
//!     checker
//! }
//!
//! # tokio_test::block_on(async {
//! let admin_user = User {
//!     id: Uuid::new_v4(),
//!     roles: vec!["admin".into()],
//! };
//!
//! let owner_user = User {
//!     id: Uuid::new_v4(),
//!     roles: vec!["user".into()],
//! };
//!
//! let document = Document {
//!     id: Uuid::new_v4(),
//!     owner_id: owner_user.id,
//! };
//!
//! let checker = create_document_checker();
//!
//! // An admin should have access.
//! assert!(checker.evaluate_access(&admin_user, &ReadAction, &document, &EmptyContext).await.is_granted());
//!
//! // The owner should have access.
//! assert!(checker.evaluate_access(&owner_user, &ReadAction, &document, &EmptyContext).await.is_granted());
//!
//! // A random user should be denied access.
//! let random_user = User {
//!     id: Uuid::new_v4(),
//!     roles: vec!["user".into()],
//! };
//! assert!(!checker.evaluate_access(&random_user, &ReadAction, &document, &EmptyContext).await.is_granted());
//! # });
//! ```
//!
//! ## Evaluation Tracing
//!
//! The permission system provides detailed tracing of policy decisions, see [`AccessEvaluation`]
//! for an example.
//!
//!
//! ## Combinators
//!
//! Sometimes you may want to require that several policies pass (AND), require that
//! at least one passes (OR), or even invert a policy (NOT). `gatehouse` provides
//! combinators for this purpose:
//!
//! - [`AndPolicy`]: Grants access only if all inner policies allow access. Otherwise,
//!   returns a combined error.
//! - [`OrPolicy`]: Grants access if any inner policy allows access; otherwise returns a
//!   combined error.
//! - [`NotPolicy`]: Inverts the decision of an inner policy.
//!
//!

#![warn(missing_docs)]
#![allow(clippy::type_complexity)]
use async_trait::async_trait;
use std::fmt;
use std::sync::Arc;

const DEFAULT_SECURITY_RULE_CATEGORY: &str = "Access Control";
const PERMISSION_CHECKER_POLICY_TYPE: &str = "PermissionChecker";

/// Metadata describing the security rule associated with a [`Policy`].
///
/// These fields follow the OpenTelemetry semantic conventions for security
/// rules: <https://opentelemetry.io/docs/specs/semconv/registry/attributes/security-rule/>.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SecurityRuleMetadata {
    name: Option<String>,
    category: Option<String>,
    description: Option<String>,
    reference: Option<String>,
    ruleset_name: Option<String>,
    uuid: Option<String>,
    version: Option<String>,
    license: Option<String>,
}

impl SecurityRuleMetadata {
    /// Creates an empty metadata container.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the `security_rule.name` attribute.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the `security_rule.category` attribute.
    pub fn with_category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    /// Sets the `security_rule.description` attribute.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the `security_rule.reference` attribute.
    pub fn with_reference(mut self, reference: impl Into<String>) -> Self {
        self.reference = Some(reference.into());
        self
    }

    /// Sets the `security_rule.ruleset.name` attribute.
    pub fn with_ruleset_name(mut self, ruleset_name: impl Into<String>) -> Self {
        self.ruleset_name = Some(ruleset_name.into());
        self
    }

    /// Sets the `security_rule.uuid` attribute.
    pub fn with_uuid(mut self, uuid: impl Into<String>) -> Self {
        self.uuid = Some(uuid.into());
        self
    }

    /// Sets the `security_rule.version` attribute.
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Sets the `security_rule.license` attribute.
    pub fn with_license(mut self, license: impl Into<String>) -> Self {
        self.license = Some(license.into());
        self
    }

    /// Returns the configured `security_rule.name` value.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the configured `security_rule.category` value.
    pub fn category(&self) -> Option<&str> {
        self.category.as_deref()
    }

    /// Returns the configured `security_rule.description` value.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// Returns the configured `security_rule.reference` value.
    pub fn reference(&self) -> Option<&str> {
        self.reference.as_deref()
    }

    /// Returns the configured `security_rule.ruleset.name` value.
    pub fn ruleset_name(&self) -> Option<&str> {
        self.ruleset_name.as_deref()
    }

    /// Returns the configured `security_rule.uuid` value.
    pub fn uuid(&self) -> Option<&str> {
        self.uuid.as_deref()
    }

    /// Returns the configured `security_rule.version` value.
    pub fn version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// Returns the configured `security_rule.license` value.
    pub fn license(&self) -> Option<&str> {
        self.license.as_deref()
    }
}

/// The type of boolean combining operation a policy might represent.
#[derive(Debug, PartialEq, Clone)]
pub enum CombineOp {
    /// All inner policies must grant access.
    And,
    /// At least one inner policy must grant access.
    Or,
    /// The inner policy's decision is inverted.
    Not,
}

impl fmt::Display for CombineOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CombineOp::And => write!(f, "AND"),
            CombineOp::Or => write!(f, "OR"),
            CombineOp::Not => write!(f, "NOT"),
        }
    }
}

/// The result of evaluating a single policy (or a combination).
///
/// This enum is used both by individual policies and by combinators to represent the
/// outcome of access evaluation.
///
/// - [`PolicyEvalResult::Granted`]: Indicates that access is granted, with an optional reason.
/// - [`PolicyEvalResult::Denied`]: Indicates that access is denied, along with an explanatory reason.
/// - [`PolicyEvalResult::Combined`]: Represents the aggregate result of combining multiple policies.
#[derive(Debug, Clone)]
pub enum PolicyEvalResult {
    /// Access granted. Contains the policy type and an optional reason.
    Granted {
        /// The name of the policy that granted access.
        policy_type: String,
        /// An optional human-readable reason for the grant.
        reason: Option<String>,
    },
    /// Access denied. Contains the policy type and a reason.
    Denied {
        /// The name of the policy that denied access.
        policy_type: String,
        /// A human-readable reason for the denial.
        reason: String,
    },
    /// Combined result from multiple policy evaluations.
    /// Contains the policy type, the combining operation ([`CombineOp`]),
    /// a list of child evaluation results, and the overall outcome.
    Combined {
        /// The name of the combinator policy (e.g. `"AndPolicy"`).
        policy_type: String,
        /// The boolean operation used to combine child results.
        operation: CombineOp,
        /// The individual results from each child policy.
        children: Vec<PolicyEvalResult>,
        /// The overall outcome after applying the combining operation.
        outcome: bool,
    },
}

/// The complete result of a permission evaluation.
/// Contains both the final decision and a detailed trace for debugging.
///
/// ### Evaluation Tracing
///
/// The permission system provides detailed tracing of policy decisions:
/// ```rust
/// # use gatehouse::*;
/// # use uuid::Uuid;
/// #
/// # // Define simple types for the example
/// # #[derive(Debug, Clone)]
/// # struct User { id: Uuid }
/// # #[derive(Debug, Clone)]
/// # struct Document { id: Uuid }
/// # #[derive(Debug, Clone)]
/// # struct ReadAction;
/// # #[derive(Debug, Clone)]
/// # struct EmptyContext;
/// #
/// # async fn example() -> AccessEvaluation {
/// #     let mut checker = PermissionChecker::<User, Document, ReadAction, EmptyContext>::new();
/// #     let user = User { id: Uuid::new_v4() };
/// #     let document = Document { id: Uuid::new_v4() };
/// #     checker.evaluate_access(&user, &ReadAction, &document, &EmptyContext).await
/// # }
/// #
/// # tokio_test::block_on(async {
/// let result = example().await;
///
/// match result {
///     AccessEvaluation::Granted { policy_type, reason, trace } => {
///         println!("Access granted by {}: {:?}", policy_type, reason);
///         println!("Full evaluation trace:\n{}", trace.format());
///     }
///     AccessEvaluation::Denied { reason, trace } => {
///         println!("Access denied: {}", reason);
///         println!("Full evaluation trace:\n{}", trace.format());
///     }
/// }
/// # });
/// ```
#[derive(Debug, Clone)]
pub enum AccessEvaluation {
    /// Access was granted.
    Granted {
        /// The policy that granted access
        policy_type: String,
        /// Optional reason for granting
        reason: Option<String>,
        /// Full evaluation trace including any rejected policies
        trace: EvalTrace,
    },
    /// Access was denied.
    Denied {
        /// The complete evaluation trace showing all policy decisions
        trace: EvalTrace,
        /// Summary reason for denial
        reason: String,
    },
}

impl AccessEvaluation {
    /// Whether access was granted
    pub fn is_granted(&self) -> bool {
        matches!(self, Self::Granted { .. })
    }

    /// Converts the evaluation into a `Result`, mapping a denial into an error.
    ///
    /// `error_fn` receives the denial reason string and should return your
    /// application's error type.
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # #[derive(Debug, Clone)]
    /// # struct User;
    /// # #[derive(Debug, Clone)]
    /// # struct Resource;
    /// # #[derive(Debug, Clone)]
    /// # struct Action;
    /// # #[derive(Debug, Clone)]
    /// # struct Ctx;
    /// # tokio_test::block_on(async {
    /// let checker = PermissionChecker::<User, Resource, Action, Ctx>::new();
    /// let result = checker.evaluate_access(&User, &Action, &Resource, &Ctx).await;
    ///
    /// // Map a denial into a standard error:
    /// let outcome: Result<(), String> = result.to_result(|reason| reason.to_string());
    /// assert!(outcome.is_err());
    /// # });
    /// ```
    pub fn to_result<E>(&self, error_fn: impl FnOnce(&str) -> E) -> Result<(), E> {
        match self {
            Self::Granted { .. } => Ok(()),
            Self::Denied { reason, .. } => Err(error_fn(reason)),
        }
    }

    /// Returns a human-readable string containing both the decision headline
    /// and the full evaluation trace tree.
    ///
    /// Useful for logging or debugging. The output includes the `Display`
    /// representation (e.g. `[GRANTED] by AdminPolicy - User is admin`)
    /// followed by the indented trace from [`EvalTrace::format`].
    pub fn display_trace(&self) -> String {
        let trace = match self {
            AccessEvaluation::Granted {
                policy_type: _,
                reason: _,
                trace,
            } => trace,
            AccessEvaluation::Denied { reason: _, trace } => trace,
        };

        // If there's an actual tree to show, add it. Otherwise, fallback.
        let trace_str = trace.format();
        if trace_str == "No evaluation trace available" {
            format!("{}\n(No evaluation trace available)", self)
        } else {
            format!("{}\nEvaluation Trace:\n{}", self, trace_str)
        }
    }
}

/// A concise line about the final decision.
impl fmt::Display for AccessEvaluation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Granted {
                policy_type,
                reason,
                trace: _,
            } => {
                // Headline
                match reason {
                    Some(r) => write!(f, "[GRANTED] by {} - {}", policy_type, r),
                    None => write!(f, "[GRANTED] by {}", policy_type),
                }
            }
            Self::Denied { reason, trace: _ } => {
                write!(f, "[Denied] - {}", reason)
            }
        }
    }
}

/// A tree of [`PolicyEvalResult`] nodes capturing every policy decision made
/// during an access evaluation.
///
/// Returned as part of [`AccessEvaluation`]. Use [`EvalTrace::format`] to render
/// a human-readable tree, useful for debugging and audit logging.
///
/// # Example
///
/// ```rust
/// # use gatehouse::*;
/// // An empty trace produces a fallback message:
/// let empty = EvalTrace::new();
/// assert_eq!(empty.format(), "No evaluation trace available");
///
/// // A trace built from a policy result renders a decision tree:
/// let trace = EvalTrace::with_root(PolicyEvalResult::Granted {
///     policy_type: "AdminPolicy".into(),
///     reason: Some("User is admin".into()),
/// });
/// assert!(trace.format().contains("AdminPolicy GRANTED"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct EvalTrace {
    root: Option<PolicyEvalResult>,
}

impl EvalTrace {
    /// Creates an empty trace with no evaluation results.
    pub fn new() -> Self {
        Self { root: None }
    }

    /// Creates a trace with the given [`PolicyEvalResult`] as the root node.
    pub fn with_root(result: PolicyEvalResult) -> Self {
        Self { root: Some(result) }
    }

    /// Sets (or replaces) the root node of the evaluation tree.
    pub fn set_root(&mut self, result: PolicyEvalResult) {
        self.root = Some(result);
    }

    /// Returns a reference to the root [`PolicyEvalResult`], if present.
    pub fn root(&self) -> Option<&PolicyEvalResult> {
        self.root.as_ref()
    }

    /// Returns a formatted, indented representation of the evaluation tree.
    ///
    /// Each node shows a `✔` or `✘` prefix, the policy name, and the reason.
    /// Combined nodes indent their children for readability.
    pub fn format(&self) -> String {
        match &self.root {
            Some(root) => root.format(0),
            None => "No evaluation trace available".to_string(),
        }
    }
}

impl PolicyEvalResult {
    /// Returns whether this evaluation resulted in access being granted
    pub fn is_granted(&self) -> bool {
        match self {
            Self::Granted { .. } => true,
            Self::Denied { .. } => false,
            Self::Combined { outcome, .. } => *outcome,
        }
    }

    /// Returns the reason string if available
    pub fn reason(&self) -> Option<String> {
        match self {
            Self::Granted { reason, .. } => reason.clone(),
            Self::Denied { reason, .. } => Some(reason.clone()),
            Self::Combined { .. } => None,
        }
    }

    /// Formats the evaluation tree with indentation for readability
    pub fn format(&self, indent: usize) -> String {
        let indent_str = " ".repeat(indent);

        match self {
            Self::Granted {
                policy_type,
                reason,
            } => {
                let reason_text = reason
                    .as_ref()
                    .map_or("".to_string(), |r| format!(": {}", r));
                format!("{}{} GRANTED{}", indent_str, policy_type, reason_text)
            }
            Self::Denied {
                policy_type,
                reason,
            } => {
                format!("{}{} DENIED: {}", indent_str, policy_type, reason)
            }
            Self::Combined {
                policy_type,
                operation,
                children,
                outcome,
            } => {
                let outcome_char = if *outcome { "" } else { "" };
                let mut result = format!(
                    "{}{} {} ({})",
                    indent_str, outcome_char, policy_type, operation
                );

                for child in children {
                    result.push_str(&format!("\n{}", child.format(indent + 2)));
                }
                result
            }
        }
    }
}

impl fmt::Display for PolicyEvalResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tree = self.format(0);
        write!(f, "{}", tree)
    }
}

/// A generic async trait representing a single authorization policy.
/// A policy determines if a subject is allowed to perform an action on
/// a resource within a given context.
#[async_trait]
pub trait Policy<Subject, Resource, Action, Context>: Send + Sync {
    /// Evaluates whether access should be granted.
    ///
    /// # Arguments
    ///
    /// * `subject` - The entity requesting access.
    /// * `action` - The action being performed.
    /// * `resource` - The target resource.
    /// * `context` - Additional context that may affect the decision.
    ///
    /// # Returns
    ///
    /// A [`PolicyEvalResult`] indicating whether access is granted or denied.
    async fn evaluate_access(
        &self,
        subject: &Subject,
        action: &Action,
        resource: &Resource,
        context: &Context,
    ) -> PolicyEvalResult;

    /// Policy name for debugging
    fn policy_type(&self) -> String;

    /// Metadata describing the security rule that backs this policy.
    ///
    /// Implementors can override this method to surface additional semantic
    /// information. The default implementation returns empty metadata which
    /// still allows downstream telemetry to fall back to the policy type.
    fn security_rule(&self) -> SecurityRuleMetadata {
        SecurityRuleMetadata::default()
    }
}

/// A container for multiple policies, applied in an "OR" fashion.
/// (If any policy returns Ok, access is granted)
/// **Important**:
/// If no policies are added, access is always denied.
#[derive(Clone)]
pub struct PermissionChecker<S, R, A, C> {
    policies: Vec<Arc<dyn Policy<S, R, A, C>>>,
}

impl<S, R, A, C> Default for PermissionChecker<S, R, A, C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S, R, A, C> PermissionChecker<S, R, A, C> {
    /// Creates a new `PermissionChecker` with no policies.
    pub fn new() -> Self {
        Self {
            policies: Vec::new(),
        }
    }

    /// Adds a policy to the checker.
    ///
    /// # Arguments
    ///
    /// * `policy` - A type implementing [`Policy`]. It is stored as an `Arc` for shared ownership.
    pub fn add_policy<P: Policy<S, R, A, C> + 'static>(&mut self, policy: P) {
        self.policies.push(Arc::new(policy));
    }

    /// Evaluates all policies against the given parameters.
    ///
    /// Policies are evaluated sequentially with OR semantics (short-circuiting on first success).
    /// Returns an [`AccessEvaluation`] with detailed tracing.
    #[tracing::instrument(skip_all)]
    pub async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> AccessEvaluation {
        if self.policies.is_empty() {
            tracing::debug!("No policies configured");
            let result = PolicyEvalResult::Denied {
                policy_type: PERMISSION_CHECKER_POLICY_TYPE.to_string(),
                reason: "No policies configured".to_string(),
            };

            return AccessEvaluation::Denied {
                trace: EvalTrace::with_root(result),
                reason: "No policies configured".to_string(),
            };
        }
        tracing::trace!(num_policies = self.policies.len(), "Checking access");

        let mut policy_results = Vec::with_capacity(self.policies.len());

        // Evaluate each policy
        for policy in &self.policies {
            let result = policy
                .evaluate_access(subject, action, resource, context)
                .await;
            let result_passes = result.is_granted();

            // Extract metadata for tracing (always needed for security audit)
            let policy_type = policy.policy_type();
            let policy_type_str = policy_type.as_str();
            let metadata = policy.security_rule();
            let reason = result.reason();
            let reason_str = reason.as_deref();
            let rule_name = metadata.name().unwrap_or(policy_type_str);
            let category = metadata
                .category()
                .unwrap_or(DEFAULT_SECURITY_RULE_CATEGORY);
            let ruleset_name = metadata
                .ruleset_name()
                .unwrap_or(PERMISSION_CHECKER_POLICY_TYPE);
            let event_outcome = if result_passes { "success" } else { "failure" };

            tracing::trace!(
                target: "gatehouse::security",
                {
                    security_rule.name = rule_name,
                    security_rule.category = category,
                    security_rule.description = metadata.description(),
                    security_rule.reference = metadata.reference(),
                    security_rule.ruleset.name = ruleset_name,
                    security_rule.uuid = metadata.uuid(),
                    security_rule.version = metadata.version(),
                    security_rule.license = metadata.license(),
                    event.outcome = event_outcome,
                    policy.type = policy_type_str,
                    policy.result.reason = reason_str,
                },
                "Security rule evaluated"
            );

            policy_results.push(result);

            // If any policy allows access, return immediately
            if result_passes {
                let combined = PolicyEvalResult::Combined {
                    policy_type: PERMISSION_CHECKER_POLICY_TYPE.to_string(),
                    operation: CombineOp::Or,
                    children: policy_results,
                    outcome: true,
                };

                return AccessEvaluation::Granted {
                    policy_type,
                    reason,
                    trace: EvalTrace::with_root(combined),
                };
            }
        }

        // If all policies denied access
        tracing::trace!("No policies allowed access, returning Forbidden");
        let combined = PolicyEvalResult::Combined {
            policy_type: PERMISSION_CHECKER_POLICY_TYPE.to_string(),
            operation: CombineOp::Or,
            children: policy_results,
            outcome: false,
        };

        AccessEvaluation::Denied {
            trace: EvalTrace::with_root(combined),
            reason: "All policies denied access".to_string(),
        }
    }
}

/// Represents the intended effect of a policy.
///
/// `Allow` means the policy grants access; `Deny` means it denies access.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
    /// The policy grants access when its predicates pass.
    Allow,
    /// The policy denies access when its predicates pass.
    Deny,
}

/// An internal policy type (not exposed to API users) that is constructed via the builder.
struct InternalPolicy<S, R, A, C> {
    name: String,
    effect: Effect,
    // The predicate returns true if all conditions pass.
    predicate: Box<dyn Fn(&S, &A, &R, &C) -> bool + Send + Sync>,
}

#[async_trait]
impl<S, R, A, C> Policy<S, R, A, C> for InternalPolicy<S, R, A, C>
where
    S: Send + Sync,
    R: Send + Sync,
    A: Send + Sync,
    C: Send + Sync,
{
    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        if (self.predicate)(subject, action, resource, context) {
            match self.effect {
                Effect::Allow => PolicyEvalResult::Granted {
                    policy_type: self.name.clone(),
                    reason: Some("Policy allowed access".into()),
                },
                Effect::Deny => PolicyEvalResult::Denied {
                    policy_type: self.name.clone(),
                    reason: "Policy denied access".into(),
                },
            }
        } else {
            // Predicate didn't match – treat as non-applicable (denied).
            PolicyEvalResult::Denied {
                policy_type: self.name.clone(),
                reason: "Policy predicate did not match".into(),
            }
        }
    }
    fn policy_type(&self) -> String {
        self.name.clone()
    }
}

// Tell the compiler that a Box<dyn Policy> implements the Policy trait so we can keep
// our internal policy type private.
#[async_trait]
impl<S, R, A, C> Policy<S, R, A, C> for Box<dyn Policy<S, R, A, C>>
where
    S: Send + Sync,
    R: Send + Sync,
    A: Send + Sync,
    C: Send + Sync,
{
    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        (**self)
            .evaluate_access(subject, action, resource, context)
            .await
    }

    fn policy_type(&self) -> String {
        (**self).policy_type()
    }

    fn security_rule(&self) -> SecurityRuleMetadata {
        (**self).security_rule()
    }
}

/// A builder API for creating custom policies.
///
/// A fluent interface to combine predicate functions on the subject, action, resource,
/// and context. All predicates are combined with AND logic — every predicate must pass
/// for the policy to grant access. Use [`PolicyBuilder::build`] to produce a boxed
/// [`Policy`] that can be added to a [`PermissionChecker`].
///
/// # Example
///
/// ```rust
/// # use gatehouse::*;
/// # use uuid::Uuid;
/// #[derive(Debug, Clone)]
/// struct User { id: Uuid, roles: Vec<String> }
/// #[derive(Debug, Clone)]
/// struct Document { owner_id: Uuid, classification: String }
/// #[derive(Debug, Clone)]
/// struct Action(String);
/// #[derive(Debug, Clone)]
/// struct Ctx;
///
/// let policy = PolicyBuilder::<User, Document, Action, Ctx>::new("OwnerEditors")
///     .subjects(|user: &User| user.roles.iter().any(|r| r == "editor"))
///     .actions(|action: &Action| action.0 == "edit")
///     .resources(|doc: &Document| doc.classification != "top-secret")
///     // Use `when` when a predicate needs to compare multiple inputs:
///     .when(|user: &User, _action: &Action, doc: &Document, _ctx: &Ctx| {
///         user.id == doc.owner_id
///     })
///     .build();
///
/// let mut checker = PermissionChecker::new();
/// checker.add_policy(policy);
///
/// # tokio_test::block_on(async {
/// let user_id = Uuid::new_v4();
/// let user = User { id: user_id, roles: vec!["editor".into()] };
/// let doc = Document { owner_id: user_id, classification: "internal".into() };
///
/// // User is an editor, action is "edit", doc is not top-secret, and user owns it:
/// assert!(checker.evaluate_access(&user, &Action("edit".into()), &doc, &Ctx).await.is_granted());
///
/// // Wrong action — predicate fails:
/// assert!(!checker.evaluate_access(&user, &Action("delete".into()), &doc, &Ctx).await.is_granted());
/// # });
/// ```
pub struct PolicyBuilder<S, R, A, C>
where
    S: Send + Sync + 'static,
    R: Send + Sync + 'static,
    A: Send + Sync + 'static,
    C: Send + Sync + 'static,
{
    name: String,
    effect: Effect,
    subject_pred: Option<Box<dyn Fn(&S) -> bool + Send + Sync>>,
    action_pred: Option<Box<dyn Fn(&A) -> bool + Send + Sync>>,
    resource_pred: Option<Box<dyn Fn(&R) -> bool + Send + Sync>>,
    context_pred: Option<Box<dyn Fn(&C) -> bool + Send + Sync>>,
    // Note the order here matches the evaluate_access signature
    extra_condition: Option<Box<dyn Fn(&S, &A, &R, &C) -> bool + Send + Sync>>,
}

impl<Subject, Resource, Action, Context> PolicyBuilder<Subject, Resource, Action, Context>
where
    Subject: Send + Sync + 'static,
    Resource: Send + Sync + 'static,
    Action: Send + Sync + 'static,
    Context: Send + Sync + 'static,
{
    /// Creates a new policy builder with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            effect: Effect::Allow,
            subject_pred: None,
            action_pred: None,
            resource_pred: None,
            context_pred: None,
            extra_condition: None,
        }
    }

    /// Sets the effect (Allow or Deny) for the policy.
    /// Defaults to Allow
    pub fn effect(mut self, effect: Effect) -> Self {
        self.effect = effect;
        self
    }

    /// Adds a predicate that tests the subject.
    pub fn subjects<F>(mut self, pred: F) -> Self
    where
        F: Fn(&Subject) -> bool + Send + Sync + 'static,
    {
        self.subject_pred = Some(Box::new(pred));
        self
    }

    /// Adds a predicate that tests the action.
    pub fn actions<F>(mut self, pred: F) -> Self
    where
        F: Fn(&Action) -> bool + Send + Sync + 'static,
    {
        self.action_pred = Some(Box::new(pred));
        self
    }

    /// Adds a predicate that tests the resource.
    pub fn resources<F>(mut self, pred: F) -> Self
    where
        F: Fn(&Resource) -> bool + Send + Sync + 'static,
    {
        self.resource_pred = Some(Box::new(pred));
        self
    }

    /// Add a predicate that validates the context.
    pub fn context<F>(mut self, pred: F) -> Self
    where
        F: Fn(&Context) -> bool + Send + Sync + 'static,
    {
        self.context_pred = Some(Box::new(pred));
        self
    }

    /// Add a condition that considers all four inputs.
    pub fn when<F>(mut self, pred: F) -> Self
    where
        F: Fn(&Subject, &Action, &Resource, &Context) -> bool + Send + Sync + 'static,
    {
        self.extra_condition = Some(Box::new(pred));
        self
    }

    /// Build the policy. Returns a boxed policy that can be added to a PermissionChecker.
    pub fn build(self) -> Box<dyn Policy<Subject, Resource, Action, Context>> {
        let effect = self.effect;
        let subject_pred = self.subject_pred;
        let action_pred = self.action_pred;
        let resource_pred = self.resource_pred;
        let context_pred = self.context_pred;
        let extra_condition = self.extra_condition;

        let predicate = Box::new(move |s: &Subject, a: &Action, r: &Resource, c: &Context| {
            subject_pred.as_ref().is_none_or(|f| f(s))
                && action_pred.as_ref().is_none_or(|f| f(a))
                && resource_pred.as_ref().is_none_or(|f| f(r))
                && context_pred.as_ref().is_none_or(|f| f(c))
                && extra_condition.as_ref().is_none_or(|f| f(s, a, r, c))
        });

        Box::new(InternalPolicy {
            name: self.name,
            effect,
            predicate,
        })
    }
}

/// A role-based access control policy.
///
/// `required_roles_resolver` is a closure that determines which roles are required
/// for the given (resource, action). `user_roles_resolver` extracts the subject's roles.
/// Access is granted if the subject holds at least one of the required roles.
///
/// Roles are identified by [`Uuid`](uuid::Uuid), allowing integration with external
/// identity systems without relying on string matching.
///
/// # Example
///
/// ```rust
/// # use gatehouse::*;
/// # use uuid::Uuid;
/// #[derive(Debug, Clone)]
/// struct User { role_ids: Vec<Uuid> }
/// #[derive(Debug, Clone)]
/// struct Resource;
/// #[derive(Debug, Clone)]
/// struct Action;
/// #[derive(Debug, Clone)]
/// struct Ctx;
///
/// let editor_role = Uuid::new_v4();
///
/// let rbac = RbacPolicy::new(
///     // required_roles_resolver: which roles can access this resource/action?
///     move |_resource: &Resource, _action: &Action| vec![editor_role],
///     // user_roles_resolver: which roles does this user have?
///     |user: &User| user.role_ids.clone(),
/// );
///
/// let mut checker = PermissionChecker::new();
/// checker.add_policy(rbac);
///
/// # tokio_test::block_on(async {
/// let authorised = User { role_ids: vec![editor_role] };
/// assert!(checker.evaluate_access(&authorised, &Action, &Resource, &Ctx).await.is_granted());
///
/// let unauthorised = User { role_ids: vec![Uuid::new_v4()] };
/// assert!(!checker.evaluate_access(&unauthorised, &Action, &Resource, &Ctx).await.is_granted());
/// # });
/// ```
pub struct RbacPolicy<S, F1, F2> {
    required_roles_resolver: F1,
    user_roles_resolver: F2,
    _marker: std::marker::PhantomData<S>,
}

impl<S, F1, F2> RbacPolicy<S, F1, F2> {
    /// Creates a new RBAC policy from two resolver closures.
    pub fn new(required_roles_resolver: F1, user_roles_resolver: F2) -> Self {
        Self {
            required_roles_resolver,
            user_roles_resolver,
            _marker: std::marker::PhantomData,
        }
    }
}

#[async_trait]
impl<S, R, A, C, F1, F2> Policy<S, R, A, C> for RbacPolicy<S, F1, F2>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
    F1: Fn(&R, &A) -> Vec<uuid::Uuid> + Sync + Send,
    F2: Fn(&S) -> Vec<uuid::Uuid> + Sync + Send,
{
    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        _context: &C,
    ) -> PolicyEvalResult {
        let required_roles = (self.required_roles_resolver)(resource, action);
        let user_roles = (self.user_roles_resolver)(subject);
        let has_role = required_roles.iter().any(|role| user_roles.contains(role));

        if has_role {
            PolicyEvalResult::Granted {
                policy_type: Policy::<S, R, A, C>::policy_type(self),
                reason: Some("User has required role".to_string()),
            }
        } else {
            PolicyEvalResult::Denied {
                policy_type: Policy::<S, R, A, C>::policy_type(self),
                reason: "User doesn't have required role".to_string(),
            }
        }
    }

    fn policy_type(&self) -> String {
        "RbacPolicy".to_string()
    }
}

/// An attribute-based access control policy.
/// Define a `condition` closure that determines whether a subject is allowed to
/// perform an action on a resource, given the additional context. If it returns
/// true, access is granted. Otherwise, access is denied.
///
/// ## Example
///
/// We define simple types for a user, a resource, an action, and a context.
/// We then create a built-in ABAC policy that grants access if the user "owns"
/// a resource as determined by the resource's owner_id.
///
/// ```rust
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use uuid::Uuid;
/// # use gatehouse::*;
///
/// // Define our core types.
/// #[derive(Debug, Clone)]
/// struct User {
///     id: Uuid,
/// }
///
/// #[derive(Debug, Clone)]
/// struct Resource {
///     owner_id: Uuid,
/// }
///
/// #[derive(Debug, Clone)]
/// struct Action;
///
/// #[derive(Debug, Clone)]
/// struct EmptyContext;
///
/// // Create an ABAC policy.
/// // This policy grants access if the user's ID matches the resource's owner.
/// let abac_policy = AbacPolicy::new(
///     |user: &User, resource: &Resource, _action: &Action, _context: &EmptyContext| {
///         user.id == resource.owner_id
///     },
/// );
///
/// // Create a PermissionChecker and add the ABAC policy.
/// let mut checker = PermissionChecker::<User, Resource, Action, EmptyContext>::new();
/// checker.add_policy(abac_policy);
///
/// // Create a sample user
/// let user = User {
///     id: Uuid::new_v4(),
/// };
///
/// // Create a resource owned by the user, and one that is not
/// let owned_resource = Resource { owner_id: user.id };
/// let other_resource = Resource { owner_id: Uuid::new_v4() };
/// let context = EmptyContext;
///
/// # tokio_test::block_on(async {
/// // This check should succeed because the user is the owner:
/// assert!(checker.evaluate_access(&user, &Action, &owned_resource, &context).await.is_granted());
///
/// // This check should fail because the user is not the owner:
/// assert!(!checker.evaluate_access(&user, &Action, &other_resource, &context).await.is_granted());
/// # });
/// ```
///
pub struct AbacPolicy<S, R, A, C, F> {
    condition: F,
    _marker: std::marker::PhantomData<(S, R, A, C)>,
}

impl<S, R, A, C, F> AbacPolicy<S, R, A, C, F> {
    /// Creates a new ABAC policy from a condition closure.
    pub fn new(condition: F) -> Self {
        Self {
            condition,
            _marker: std::marker::PhantomData,
        }
    }
}

#[async_trait]
impl<S, R, A, C, F> Policy<S, R, A, C> for AbacPolicy<S, R, A, C, F>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
    F: Fn(&S, &R, &A, &C) -> bool + Sync + Send,
{
    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        let condition_met = (self.condition)(subject, resource, action, context);

        if condition_met {
            PolicyEvalResult::Granted {
                policy_type: self.policy_type(),
                reason: Some("Condition evaluated to true".to_string()),
            }
        } else {
            PolicyEvalResult::Denied {
                policy_type: self.policy_type(),
                reason: "Condition evaluated to false".to_string(),
            }
        }
    }

    fn policy_type(&self) -> String {
        "AbacPolicy".to_string()
    }
}

/// A trait that abstracts a relationship resolver.
/// Given a subject and a resource, the resolver answers whether the
/// specified relationship e.g. "creator", "manager" exists between them.
///
/// The relationship type `Re` is generic, so you can use strings, enums, or
/// other domain-specific types.
#[async_trait]
pub trait RelationshipResolver<S, R, Re>: Send + Sync {
    /// Returns `true` if `relationship` exists between `subject` and `resource`.
    async fn has_relationship(&self, subject: &S, resource: &R, relationship: &Re) -> bool;
}

/// ### ReBAC Policy
///
/// In this example, we show how to use a built-in relationship-based (ReBAC) policy. We define
/// a dummy relationship resolver that checks if a user is the manager of a project.
///
/// ```rust
/// use async_trait::async_trait;
/// use std::sync::Arc;
/// use uuid::Uuid;
/// use gatehouse::*;
///
/// #[derive(Debug, Clone)]
/// pub struct Employee {
///     pub id: Uuid,
/// }
///
/// #[derive(Debug, Clone)]
/// pub struct Project {
///     pub id: Uuid,
///     pub manager_id: Uuid,
/// }
///
/// #[derive(Debug, Clone)]
/// pub struct AccessAction;
///
/// #[derive(Debug, Clone)]
/// pub struct EmptyContext;
///
/// // Define a dummy relationship resolver that considers an employee to be a manager
/// // of a project if their id matches the project's manager_id.
/// struct DummyRelationshipResolver;
///
/// #[async_trait]
/// impl RelationshipResolver<Employee, Project, String> for DummyRelationshipResolver {
///     async fn has_relationship(
///         &self,
///         employee: &Employee,
///         project: &Project,
///         relationship: &String,
///     ) -> bool {
///         relationship == "manager" && employee.id == project.manager_id
///     }
/// }
///
/// // Create a ReBAC policy that checks for the "manager" relationship.
/// let rebac_policy = RebacPolicy::<Employee, Project, AccessAction, EmptyContext, _, _>::new(
///     "manager".to_string(),
///     DummyRelationshipResolver,
/// );
///
/// // Create a PermissionChecker and add the ReBAC policy.
/// let mut checker = PermissionChecker::<Employee, Project, AccessAction, EmptyContext>::new();
/// checker.add_policy(rebac_policy);
///
/// // Create a sample employee and project.
/// let manager = Employee { id: Uuid::new_v4() };
/// let project = Project {
///     id: Uuid::new_v4(),
///     manager_id: manager.id,
/// };
/// let context = EmptyContext;
///
/// // The manager should have access.
/// # tokio_test::block_on(async {
/// assert!(checker.evaluate_access(&manager, &AccessAction, &project, &context).await.is_granted());
///
/// // A different employee should be denied access.
/// let other_employee = Employee { id: Uuid::new_v4() };
/// assert!(!checker.evaluate_access(&other_employee, &AccessAction, &project, &context).await.is_granted());
/// # });
/// ```
///
/// The relationship type `Re` must implement [`fmt::Display`] so that policy
/// evaluation reasons can include the relationship value in log messages.
pub struct RebacPolicy<S, R, A, C, Re, RG> {
    /// The relationship to check (e.g. `"manager"`, or an enum variant).
    pub relationship: Re,
    /// The resolver that determines whether the relationship exists.
    pub resolver: RG,
    _marker: std::marker::PhantomData<(S, R, A, C)>,
}

impl<S, R, A, C, Re, RG> RebacPolicy<S, R, A, C, Re, RG> {
    /// Creates a new `RebacPolicy` for a given relationship.
    pub fn new(relationship: Re, resolver: RG) -> Self {
        Self {
            relationship,
            resolver,
            _marker: std::marker::PhantomData,
        }
    }
}

#[async_trait]
impl<S, R, A, C, Re, RG> Policy<S, R, A, C> for RebacPolicy<S, R, A, C, Re, RG>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
    Re: Sync + Send + fmt::Display,
    RG: RelationshipResolver<S, R, Re>,
{
    async fn evaluate_access(
        &self,
        subject: &S,
        _action: &A,
        resource: &R,
        _context: &C,
    ) -> PolicyEvalResult {
        let has_relationship = self
            .resolver
            .has_relationship(subject, resource, &self.relationship)
            .await;

        if has_relationship {
            PolicyEvalResult::Granted {
                policy_type: self.policy_type(),
                reason: Some(format!(
                    "Subject has '{}' relationship with resource",
                    self.relationship
                )),
            }
        } else {
            PolicyEvalResult::Denied {
                policy_type: self.policy_type(),
                reason: format!(
                    "Subject does not have '{}' relationship with resource",
                    self.relationship
                ),
            }
        }
    }

    fn policy_type(&self) -> String {
        "RebacPolicy".to_string()
    }
}

/// ---
/// Policy Combinators
/// ---
///
/// AndPolicy
///
/// Combines multiple policies with a logical AND. Access is granted only if every
/// inner policy grants access.
pub struct AndPolicy<S, R, A, C> {
    policies: Vec<Arc<dyn Policy<S, R, A, C>>>,
}

/// Error returned when no policies are provided to a combinator policy.
#[derive(Debug, Copy, Clone)]
pub struct EmptyPoliciesError(pub &'static str);

impl<S, R, A, C> AndPolicy<S, R, A, C> {
    /// Creates a new `AndPolicy` from a non-empty list of policies.
    ///
    /// Returns [`EmptyPoliciesError`] if `policies` is empty.
    pub fn try_new(policies: Vec<Arc<dyn Policy<S, R, A, C>>>) -> Result<Self, EmptyPoliciesError> {
        if policies.is_empty() {
            Err(EmptyPoliciesError(
                "AndPolicy must have at least one policy",
            ))
        } else {
            Ok(Self { policies })
        }
    }
}

#[async_trait]
impl<S, R, A, C> Policy<S, R, A, C> for AndPolicy<S, R, A, C>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
{
    // Override the default policy_type implementation
    fn policy_type(&self) -> String {
        "AndPolicy".to_string()
    }

    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        let mut children_results = Vec::with_capacity(self.policies.len());

        for policy in &self.policies {
            let result = policy
                .evaluate_access(subject, action, resource, context)
                .await;
            let is_granted = result.is_granted();
            children_results.push(result);

            // Short-circuit on first denial
            if !is_granted {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::And,
                    children: children_results,
                    outcome: false,
                };
            }
        }

        // All policies granted access
        PolicyEvalResult::Combined {
            policy_type: self.policy_type(),
            operation: CombineOp::And,
            children: children_results,
            outcome: true,
        }
    }
}

/// OrPolicy
///
/// Combines multiple policies with a logical OR. Access is granted if any inner policy
/// grants access.
pub struct OrPolicy<S, R, A, C> {
    policies: Vec<Arc<dyn Policy<S, R, A, C>>>,
}

impl<S, R, A, C> OrPolicy<S, R, A, C> {
    /// Creates a new `OrPolicy` from a non-empty list of policies.
    ///
    /// Returns [`EmptyPoliciesError`] if `policies` is empty.
    pub fn try_new(policies: Vec<Arc<dyn Policy<S, R, A, C>>>) -> Result<Self, EmptyPoliciesError> {
        if policies.is_empty() {
            Err(EmptyPoliciesError("OrPolicy must have at least one policy"))
        } else {
            Ok(Self { policies })
        }
    }
}

#[async_trait]
impl<S, R, A, C> Policy<S, R, A, C> for OrPolicy<S, R, A, C>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
{
    // Override the default policy_type implementation
    fn policy_type(&self) -> String {
        "OrPolicy".to_string()
    }
    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        let mut children_results = Vec::with_capacity(self.policies.len());

        for policy in &self.policies {
            let result = policy
                .evaluate_access(subject, action, resource, context)
                .await;
            let is_granted = result.is_granted();
            children_results.push(result);

            // Short-circuit on first success
            if is_granted {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::Or,
                    children: children_results,
                    outcome: true,
                };
            }
        }

        // All policies denied access
        PolicyEvalResult::Combined {
            policy_type: self.policy_type(),
            operation: CombineOp::Or,
            children: children_results,
            outcome: false,
        }
    }
}

/// NotPolicy
///
/// Inverts the result of an inner policy. If the inner policy allows access, then NotPolicy
/// denies it, and vice versa.
pub struct NotPolicy<S, R, A, C> {
    policy: Arc<dyn Policy<S, R, A, C>>,
}

impl<S, R, A, C> NotPolicy<S, R, A, C> {
    /// Creates a new `NotPolicy` that inverts the given policy's decision.
    pub fn new(policy: impl Policy<S, R, A, C> + 'static) -> Self {
        Self {
            policy: Arc::new(policy),
        }
    }
}

#[async_trait]
impl<S, R, A, C> Policy<S, R, A, C> for NotPolicy<S, R, A, C>
where
    S: Sync + Send,
    R: Sync + Send,
    A: Sync + Send,
    C: Sync + Send,
{
    // Override the default policy_type implementation
    fn policy_type(&self) -> String {
        "NotPolicy".to_string()
    }

    async fn evaluate_access(
        &self,
        subject: &S,
        action: &A,
        resource: &R,
        context: &C,
    ) -> PolicyEvalResult {
        let inner_result = self
            .policy
            .evaluate_access(subject, action, resource, context)
            .await;
        let is_granted = inner_result.is_granted();

        PolicyEvalResult::Combined {
            policy_type: Policy::<S, R, A, C>::policy_type(self),
            operation: CombineOp::Not,
            children: vec![inner_result],
            outcome: !is_granted,
        }
    }
}

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

    // Dummy resource/action/context types for testing
    #[derive(Debug, Clone)]
    pub struct TestSubject {
        pub id: uuid::Uuid,
    }

    #[derive(Debug, Clone)]
    pub struct TestResource {
        pub id: uuid::Uuid,
    }

    #[derive(Debug, Clone)]
    pub struct TestAction;

    #[derive(Debug, Clone)]
    pub struct TestContext;

    #[test]
    fn security_rule_metadata_builder_sets_fields() {
        let metadata = SecurityRuleMetadata::new()
            .with_name("Example")
            .with_category("Access Control")
            .with_description("Example description")
            .with_reference("https://example.com/rule")
            .with_ruleset_name("ExampleRuleset")
            .with_uuid("1234")
            .with_version("1.0.0")
            .with_license("Apache-2.0");

        assert_eq!(metadata.name(), Some("Example"));
        assert_eq!(metadata.category(), Some("Access Control"));
        assert_eq!(metadata.description(), Some("Example description"));
        assert_eq!(metadata.reference(), Some("https://example.com/rule"));
        assert_eq!(metadata.ruleset_name(), Some("ExampleRuleset"));
        assert_eq!(metadata.uuid(), Some("1234"));
        assert_eq!(metadata.version(), Some("1.0.0"));
        assert_eq!(metadata.license(), Some("Apache-2.0"));
    }

    // A policy that always allows
    struct AlwaysAllowPolicy;

    #[async_trait]
    impl Policy<TestSubject, TestResource, TestAction, TestContext> for AlwaysAllowPolicy {
        async fn evaluate_access(
            &self,
            _subject: &TestSubject,
            _action: &TestAction,
            _resource: &TestResource,
            _context: &TestContext,
        ) -> PolicyEvalResult {
            PolicyEvalResult::Granted {
                policy_type: self.policy_type(),
                reason: Some("Always allow policy".to_string()),
            }
        }

        fn policy_type(&self) -> String {
            "AlwaysAllowPolicy".to_string()
        }
    }

    // A policy that always denies, with a custom reason
    struct AlwaysDenyPolicy(&'static str);

    #[async_trait]
    impl Policy<TestSubject, TestResource, TestAction, TestContext> for AlwaysDenyPolicy {
        async fn evaluate_access(
            &self,
            _subject: &TestSubject,
            _action: &TestAction,
            _resource: &TestResource,
            _context: &TestContext,
        ) -> PolicyEvalResult {
            PolicyEvalResult::Denied {
                policy_type: self.policy_type(),
                reason: self.0.to_string(),
            }
        }

        fn policy_type(&self) -> String {
            "AlwaysDenyPolicy".to_string()
        }
    }

    #[tokio::test]
    async fn test_no_policies() {
        let checker =
            PermissionChecker::<TestSubject, TestResource, TestAction, TestContext>::new();

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        match result {
            AccessEvaluation::Denied { reason, trace: _ } => {
                assert!(reason.contains("No policies configured"));
            }
            _ => panic!("Expected Denied(No policies configured), got {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_one_policy_allow() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysAllowPolicy);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        if let AccessEvaluation::Granted {
            policy_type,
            reason,
            trace,
        } = result
        {
            assert_eq!(policy_type, "AlwaysAllowPolicy");
            assert_eq!(reason, Some("Always allow policy".to_string()));
            // Check the trace to ensure the policy was evaluated
            let trace_str = trace.format();
            assert!(trace_str.contains("AlwaysAllowPolicy"));
        } else {
            panic!("Expected AccessEvaluation::Granted, got {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_one_policy_deny() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysDenyPolicy("DeniedByPolicy"));

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert!(!result.is_granted());
        if let AccessEvaluation::Denied { reason, trace } = result {
            assert!(reason.contains("All policies denied access"));
            let trace_str = trace.format();
            assert!(trace_str.contains("DeniedByPolicy"));
        } else {
            panic!("Expected AccessEvaluation::Denied, got {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_multiple_policies_or_success() {
        // First policy denies, second allows. Checker should return Ok, short-circuiting on second.
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysDenyPolicy("DenyPolicy"));
        checker.add_policy(AlwaysAllowPolicy);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        if let AccessEvaluation::Granted {
            policy_type,
            trace,
            reason: _,
        } = result
        {
            assert_eq!(policy_type, "AlwaysAllowPolicy");
            let trace_str = trace.format();
            assert!(trace_str.contains("DenyPolicy"));
        } else {
            panic!("Expected AccessEvaluation::Granted, got {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_multiple_policies_all_deny_collect_reasons() {
        // Both policies deny, so we expect a Forbidden
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysDenyPolicy("DenyPolicy1"));
        checker.add_policy(AlwaysDenyPolicy("DenyPolicy2"));

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        if let AccessEvaluation::Denied { trace, reason } = result {
            let trace_str = trace.format();
            assert!(trace_str.contains("DenyPolicy1"));
            assert!(trace_str.contains("DenyPolicy2"));
            assert_eq!(reason, "All policies denied access");
        } else {
            panic!("Expected AccessEvaluation::Denied, got {:?}", result);
        }
    }

    // RebacPolicy tests with a dummy resolver.

    /// In-memory relationship resolver for testing.
    /// It holds a vector of tuples (subject_id, resource_id, relationship)
    /// to represent existing relationships.
    pub struct DummyRelationshipResolver {
        relationships: Vec<(uuid::Uuid, uuid::Uuid, String)>,
    }

    impl DummyRelationshipResolver {
        pub fn new(relationships: Vec<(uuid::Uuid, uuid::Uuid, String)>) -> Self {
            Self { relationships }
        }
    }

    #[async_trait]
    impl RelationshipResolver<TestSubject, TestResource, String> for DummyRelationshipResolver {
        async fn has_relationship(
            &self,
            subject: &TestSubject,
            resource: &TestResource,
            relationship: &String,
        ) -> bool {
            self.relationships
                .iter()
                .any(|(s, r, rel)| s == &subject.id && r == &resource.id && rel == relationship)
        }
    }

    #[tokio::test]
    async fn test_rebac_policy_allows_when_relationship_exists() {
        let subject_id = uuid::Uuid::new_v4();
        let resource_id = uuid::Uuid::new_v4();
        let relationship = "manager".to_string();

        let subject = TestSubject { id: subject_id };
        let resource = TestResource { id: resource_id };

        // Create a dummy resolver that knows the subject is a manager of the resource.
        let resolver =
            DummyRelationshipResolver::new(vec![(subject_id, resource_id, relationship.clone())]);

        let policy = RebacPolicy::<TestSubject, TestResource, TestAction, TestContext, _, _>::new(
            relationship,
            resolver,
        );

        // Action and context are not used by RebacPolicy, so we pass dummy values.
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert!(
            result.is_granted(),
            "Access should be allowed if relationship exists"
        );
    }

    #[tokio::test]
    async fn test_rebac_policy_denies_when_relationship_missing() {
        let subject_id = uuid::Uuid::new_v4();
        let resource_id = uuid::Uuid::new_v4();
        let relationship = "manager".to_string();

        let subject = TestSubject { id: subject_id };
        let resource = TestResource { id: resource_id };

        // Create a dummy resolver with no relationships.
        let resolver = DummyRelationshipResolver::new(vec![]);

        let policy = RebacPolicy::<TestSubject, TestResource, TestAction, TestContext, _, _>::new(
            relationship,
            resolver,
        );

        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        // Check access is denied
        assert!(
            !result.is_granted(),
            "Access should be denied if relationship does not exist"
        );
    }

    // RebacPolicy test with enum relationship type.

    #[derive(Debug, Clone, PartialEq)]
    enum TestRelation {
        Manager,
        Viewer,
    }

    impl fmt::Display for TestRelation {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                TestRelation::Manager => write!(f, "manager"),
                TestRelation::Viewer => write!(f, "viewer"),
            }
        }
    }

    struct EnumRelationshipResolver {
        relationships: Vec<(uuid::Uuid, uuid::Uuid, TestRelation)>,
    }

    #[async_trait]
    impl RelationshipResolver<TestSubject, TestResource, TestRelation> for EnumRelationshipResolver {
        async fn has_relationship(
            &self,
            subject: &TestSubject,
            resource: &TestResource,
            relationship: &TestRelation,
        ) -> bool {
            self.relationships
                .iter()
                .any(|(s, r, rel)| s == &subject.id && r == &resource.id && rel == relationship)
        }
    }

    #[tokio::test]
    async fn test_rebac_policy_with_enum_relationship() {
        let subject_id = uuid::Uuid::new_v4();
        let resource_id = uuid::Uuid::new_v4();

        let subject = TestSubject { id: subject_id };
        let resource = TestResource { id: resource_id };

        let resolver = EnumRelationshipResolver {
            relationships: vec![(subject_id, resource_id, TestRelation::Manager)],
        };

        let policy = RebacPolicy::<TestSubject, TestResource, TestAction, TestContext, _, _>::new(
            TestRelation::Manager,
            resolver,
        );

        // Manager relationship exists — should be granted.
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        assert!(
            result.is_granted(),
            "Access should be granted for matching enum relationship"
        );

        // Viewer policy with same resolver (no viewer relationship) — should be denied.
        let resolver = EnumRelationshipResolver {
            relationships: vec![(subject_id, resource_id, TestRelation::Manager)],
        };
        let viewer_policy =
            RebacPolicy::<TestSubject, TestResource, TestAction, TestContext, _, _>::new(
                TestRelation::Viewer,
                resolver,
            );

        let result = viewer_policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        assert!(
            !result.is_granted(),
            "Access should be denied when enum relationship does not match"
        );
    }

    // Combinator tests.
    #[tokio::test]
    async fn test_and_policy_allows_when_all_allow() {
        let policy = AndPolicy::try_new(vec![
            Arc::new(AlwaysAllowPolicy),
            Arc::new(AlwaysAllowPolicy),
        ])
        .expect("Unable to create and-policy policy");
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        assert!(
            result.is_granted(),
            "AndPolicy should allow access when all inner policies allow"
        );
    }
    #[tokio::test]
    async fn test_and_policy_denies_when_one_denies() {
        let policy = AndPolicy::try_new(vec![
            Arc::new(AlwaysAllowPolicy),
            Arc::new(AlwaysDenyPolicy("DenyInAnd")),
        ])
        .expect("Unable to create and-policy policy");
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        match result {
            PolicyEvalResult::Combined {
                policy_type,
                operation,
                children,
                outcome,
            } => {
                assert_eq!(operation, CombineOp::And);
                assert!(!outcome);
                assert_eq!(children.len(), 2);
                assert!(children[1].format(0).contains("DenyInAnd"));
                assert_eq!(policy_type, "AndPolicy");
            }
            _ => panic!("Expected Combined result from AndPolicy, got {:?}", result),
        }
    }
    #[tokio::test]
    async fn test_or_policy_allows_when_one_allows() {
        let policy = OrPolicy::try_new(vec![
            Arc::new(AlwaysDenyPolicy("Deny1")),
            Arc::new(AlwaysAllowPolicy),
        ])
        .expect("Unable to create or-policy policy");
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        assert!(
            result.is_granted(),
            "OrPolicy should allow access when at least one inner policy allows"
        );
    }
    #[tokio::test]
    async fn test_or_policy_denies_when_all_deny() {
        let policy = OrPolicy::try_new(vec![
            Arc::new(AlwaysDenyPolicy("Deny1")),
            Arc::new(AlwaysDenyPolicy("Deny2")),
        ])
        .expect("Unable to create or-policy policy");
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        match result {
            PolicyEvalResult::Combined {
                policy_type,
                operation,
                children,
                outcome,
            } => {
                assert_eq!(operation, CombineOp::Or);
                assert!(!outcome);
                assert_eq!(children.len(), 2);
                assert!(children[0].format(0).contains("Deny1"));
                assert!(children[1].format(0).contains("Deny2"));
                assert_eq!(policy_type, "OrPolicy");
            }
            _ => panic!("Expected Combined result from OrPolicy, got {:?}", result),
        }
    }
    #[tokio::test]
    async fn test_not_policy_allows_when_inner_denies() {
        let policy = NotPolicy::new(AlwaysDenyPolicy("AlwaysDeny"));
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        assert!(
            result.is_granted(),
            "NotPolicy should allow access when inner policy denies"
        );
    }
    #[tokio::test]
    async fn test_not_policy_denies_when_inner_allows() {
        let policy = NotPolicy::new(AlwaysAllowPolicy);
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;
        match result {
            PolicyEvalResult::Combined {
                policy_type,
                operation,
                children,
                outcome,
            } => {
                assert_eq!(operation, CombineOp::Not);
                assert!(!outcome);
                assert_eq!(children.len(), 1);
                assert!(children[0].format(0).contains("AlwaysAllowPolicy"));
                assert_eq!(policy_type, "NotPolicy");
            }
            _ => panic!("Expected Combined result from NotPolicy, got {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_empty_policies_in_combinators() {
        // Test AndPolicy with no policies
        let and_policy_result =
            AndPolicy::<TestSubject, TestResource, TestAction, TestContext>::try_new(vec![]);

        assert!(and_policy_result.is_err());

        // Test OrPolicy with no policies
        let or_policy_result =
            OrPolicy::<TestSubject, TestResource, TestAction, TestContext>::try_new(vec![]);
        assert!(or_policy_result.is_err());
    }

    #[tokio::test]
    async fn test_deeply_nested_combinators() {
        // Create a complex policy structure: NOT(AND(Allow, OR(Deny, NOT(Deny))))
        let inner_not = NotPolicy::new(AlwaysDenyPolicy("InnerDeny"));

        let inner_or = OrPolicy::try_new(vec![
            Arc::new(AlwaysDenyPolicy("MidDeny")),
            Arc::new(inner_not),
        ])
        .expect("Unable to create or-policy policy");

        let inner_and = AndPolicy::try_new(vec![Arc::new(AlwaysAllowPolicy), Arc::new(inner_or)])
            .expect("Unable to create and-policy policy");

        let outer_not = NotPolicy::new(inner_and);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = outer_not
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        // This complex structure should result in a denial
        assert!(!result.is_granted());

        // Verify the correct structure of the trace
        let trace_str = result.format(0);
        assert!(trace_str.contains("NOT"));
        assert!(trace_str.contains("AND"));
        assert!(trace_str.contains("OR"));
        assert!(trace_str.contains("InnerDeny"));
    }

    #[derive(Debug, Clone)]
    struct FeatureFlagContext {
        feature_enabled: bool,
    }

    struct FeatureFlagPolicy;

    #[async_trait]
    impl Policy<TestSubject, TestResource, TestAction, FeatureFlagContext> for FeatureFlagPolicy {
        async fn evaluate_access(
            &self,
            _subject: &TestSubject,
            _action: &TestAction,
            _resource: &TestResource,
            context: &FeatureFlagContext,
        ) -> PolicyEvalResult {
            if context.feature_enabled {
                PolicyEvalResult::Granted {
                    policy_type: self.policy_type(),
                    reason: Some("Feature flag enabled".to_string()),
                }
            } else {
                PolicyEvalResult::Denied {
                    policy_type: self.policy_type(),
                    reason: "Feature flag disabled".to_string(),
                }
            }
        }

        fn policy_type(&self) -> String {
            "FeatureFlagPolicy".to_string()
        }
    }

    #[tokio::test]
    async fn test_context_sensitive_policy() {
        let policy = FeatureFlagPolicy;
        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        // Test with flag enabled
        let context_enabled = FeatureFlagContext {
            feature_enabled: true,
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &context_enabled)
            .await;
        assert!(result.is_granted());

        // Test with flag disabled
        let context_disabled = FeatureFlagContext {
            feature_enabled: false,
        };
        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &context_disabled)
            .await;
        assert!(!result.is_granted());
    }

    // ==================== AbacPolicy Tests ====================

    #[tokio::test]
    async fn test_abac_policy_grants_when_condition_true() {
        let policy = AbacPolicy::new(
            |_subject: &TestSubject, _resource: &TestResource, _action: &TestAction, _context: &TestContext| {
                true
            },
        );

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert!(result.is_granted(), "AbacPolicy should grant when condition returns true");
        assert_eq!(policy.policy_type(), "AbacPolicy");
    }

    #[tokio::test]
    async fn test_abac_policy_denies_when_condition_false() {
        let policy = AbacPolicy::new(
            |_subject: &TestSubject, _resource: &TestResource, _action: &TestAction, _context: &TestContext| {
                false
            },
        );

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert!(!result.is_granted(), "AbacPolicy should deny when condition returns false");
        match result {
            PolicyEvalResult::Denied { policy_type, reason } => {
                assert_eq!(policy_type, "AbacPolicy");
                assert!(reason.contains("false"));
            }
            _ => panic!("Expected Denied result, got {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_abac_policy_with_attribute_check() {
        // Policy that checks if the subject owns the resource
        let policy = AbacPolicy::new(
            |subject: &TestSubject, resource: &TestResource, _action: &TestAction, _context: &TestContext| {
                subject.id == resource.id
            },
        );

        let owner_id = uuid::Uuid::new_v4();
        let owner = TestSubject { id: owner_id };
        let owned_resource = TestResource { id: owner_id };
        let other_resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        // Owner should have access to owned resource
        let result = policy
            .evaluate_access(&owner, &TestAction, &owned_resource, &TestContext)
            .await;
        assert!(result.is_granted(), "Owner should have access to owned resource");

        // Owner should not have access to other resource
        let result = policy
            .evaluate_access(&owner, &TestAction, &other_resource, &TestContext)
            .await;
        assert!(!result.is_granted(), "Owner should not have access to other resource");
    }

    // ==================== RbacPolicy Tests ====================

    #[tokio::test]
    async fn test_rbac_policy_grants_when_user_has_required_role() {
        let admin_role = uuid::Uuid::new_v4();
        let user_role = uuid::Uuid::new_v4();

        #[derive(Debug, Clone)]
        struct RbacUser {
            roles: Vec<uuid::Uuid>,
        }

        let policy = RbacPolicy::new(
            |_resource: &TestResource, _action: &TestAction| vec![admin_role],
            |subject: &RbacUser| subject.roles.clone(),
        );

        let admin_user = RbacUser {
            roles: vec![admin_role, user_role],
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result: PolicyEvalResult = Policy::<RbacUser, TestResource, TestAction, TestContext>::evaluate_access(
            &policy,
            &admin_user,
            &TestAction,
            &resource,
            &TestContext,
        )
        .await;

        assert!(result.is_granted(), "User with required role should be granted access");
        assert_eq!(
            Policy::<RbacUser, TestResource, TestAction, TestContext>::policy_type(&policy),
            "RbacPolicy"
        );
    }

    #[tokio::test]
    async fn test_rbac_policy_denies_when_user_lacks_required_role() {
        let admin_role = uuid::Uuid::new_v4();
        let user_role = uuid::Uuid::new_v4();

        #[derive(Debug, Clone)]
        struct RbacUser {
            roles: Vec<uuid::Uuid>,
        }

        let policy = RbacPolicy::new(
            |_resource: &TestResource, _action: &TestAction| vec![admin_role],
            |subject: &RbacUser| subject.roles.clone(),
        );

        let regular_user = RbacUser {
            roles: vec![user_role],
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result: PolicyEvalResult = Policy::<RbacUser, TestResource, TestAction, TestContext>::evaluate_access(
            &policy,
            &regular_user,
            &TestAction,
            &resource,
            &TestContext,
        )
        .await;

        assert!(!result.is_granted(), "User without required role should be denied");
        match result {
            PolicyEvalResult::Denied { policy_type, reason } => {
                assert_eq!(policy_type, "RbacPolicy");
                assert!(reason.contains("doesn't have required role"));
            }
            _ => panic!("Expected Denied result, got {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_rbac_policy_grants_with_any_matching_role() {
        let role1 = uuid::Uuid::new_v4();
        let role2 = uuid::Uuid::new_v4();
        let role3 = uuid::Uuid::new_v4();

        #[derive(Debug, Clone)]
        struct RbacUser {
            roles: Vec<uuid::Uuid>,
        }

        // Policy requires either role1 or role2
        let policy = RbacPolicy::new(
            |_resource: &TestResource, _action: &TestAction| vec![role1, role2],
            |subject: &RbacUser| subject.roles.clone(),
        );

        // User has role2 (one of the required roles)
        let user = RbacUser {
            roles: vec![role2, role3],
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result: PolicyEvalResult = Policy::<RbacUser, TestResource, TestAction, TestContext>::evaluate_access(
            &policy,
            &user,
            &TestAction,
            &resource,
            &TestContext,
        )
        .await;

        assert!(result.is_granted(), "User with any required role should be granted access");
    }

    #[tokio::test]
    async fn test_rbac_policy_denies_with_empty_user_roles() {
        let admin_role = uuid::Uuid::new_v4();

        #[derive(Debug, Clone)]
        struct RbacUser {
            roles: Vec<uuid::Uuid>,
        }

        let policy = RbacPolicy::new(
            |_resource: &TestResource, _action: &TestAction| vec![admin_role],
            |subject: &RbacUser| subject.roles.clone(),
        );

        let user_no_roles = RbacUser { roles: vec![] };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result: PolicyEvalResult = Policy::<RbacUser, TestResource, TestAction, TestContext>::evaluate_access(
            &policy,
            &user_no_roles,
            &TestAction,
            &resource,
            &TestContext,
        )
        .await;

        assert!(!result.is_granted(), "User with no roles should be denied");
    }

    #[tokio::test]
    async fn test_rbac_policy_denies_with_empty_required_roles() {
        let user_role = uuid::Uuid::new_v4();

        #[derive(Debug, Clone)]
        struct RbacUser {
            roles: Vec<uuid::Uuid>,
        }

        // No roles are required (empty list)
        let policy = RbacPolicy::new(
            |_resource: &TestResource, _action: &TestAction| vec![],
            |subject: &RbacUser| subject.roles.clone(),
        );

        let user = RbacUser {
            roles: vec![user_role],
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result: PolicyEvalResult = Policy::<RbacUser, TestResource, TestAction, TestContext>::evaluate_access(
            &policy,
            &user,
            &TestAction,
            &resource,
            &TestContext,
        )
        .await;

        // With empty required roles, no role can match, so access is denied
        assert!(!result.is_granted(), "Empty required roles means no match is possible");
    }

    #[tokio::test]
    async fn test_short_circuit_evaluation() {
        // Create a counter to track policy evaluation
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc as StdArc;

        let evaluation_count = StdArc::new(AtomicUsize::new(0));

        struct CountingPolicy {
            result: bool,
            counter: StdArc<AtomicUsize>,
        }

        #[async_trait]
        impl Policy<TestSubject, TestResource, TestAction, TestContext> for CountingPolicy {
            async fn evaluate_access(
                &self,
                _subject: &TestSubject,
                _action: &TestAction,
                _resource: &TestResource,
                _context: &TestContext,
            ) -> PolicyEvalResult {
                self.counter.fetch_add(1, Ordering::SeqCst);

                if self.result {
                    PolicyEvalResult::Granted {
                        policy_type: self.policy_type(),
                        reason: Some("Counting policy granted".to_string()),
                    }
                } else {
                    PolicyEvalResult::Denied {
                        policy_type: self.policy_type(),
                        reason: "Counting policy denied".to_string(),
                    }
                }
            }

            fn policy_type(&self) -> String {
                "CountingPolicy".to_string()
            }
        }

        // Test AND short circuit on first deny
        let count_clone = evaluation_count.clone();
        evaluation_count.store(0, Ordering::SeqCst);

        let and_policy = AndPolicy::try_new(vec![
            Arc::new(CountingPolicy {
                result: false,
                counter: count_clone.clone(),
            }),
            Arc::new(CountingPolicy {
                result: true,
                counter: count_clone,
            }),
        ])
        .expect("Unable to create 'and' policy");

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };
        and_policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert_eq!(
            evaluation_count.load(Ordering::SeqCst),
            1,
            "AND policy should short-circuit after first deny"
        );

        // Test OR short circuit on first allow
        let count_clone = evaluation_count.clone();
        evaluation_count.store(0, Ordering::SeqCst);

        let or_policy = OrPolicy::try_new(vec![
            Arc::new(CountingPolicy {
                result: true,
                counter: count_clone.clone(),
            }),
            Arc::new(CountingPolicy {
                result: false,
                counter: count_clone,
            }),
        ])
        .unwrap();

        or_policy
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        assert_eq!(
            evaluation_count.load(Ordering::SeqCst),
            1,
            "OR policy should short-circuit after first allow"
        );
    }

    // ==================== AccessEvaluation Tests ====================

    #[tokio::test]
    async fn test_access_evaluation_to_result_granted() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysAllowPolicy);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        // to_result should return Ok for granted access
        let converted: Result<(), String> = result.to_result(|reason| reason.to_string());
        assert!(converted.is_ok(), "to_result should return Ok for granted access");
    }

    #[tokio::test]
    async fn test_access_evaluation_to_result_denied() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysDenyPolicy("Access denied"));

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        // to_result should return Err for denied access
        let converted: Result<(), String> = result.to_result(|reason| reason.to_string());
        assert!(converted.is_err(), "to_result should return Err for denied access");
        assert!(converted.unwrap_err().contains("denied"));
    }

    #[tokio::test]
    async fn test_access_evaluation_display_trace_granted() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysAllowPolicy);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        let trace_display = result.display_trace();
        assert!(trace_display.contains("GRANTED"), "Trace should show GRANTED");
        assert!(trace_display.contains("AlwaysAllowPolicy"), "Trace should show policy name");
        assert!(trace_display.contains("Evaluation Trace"), "Trace should include trace section");
    }

    #[tokio::test]
    async fn test_access_evaluation_display_trace_denied() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysDenyPolicy("Test denial"));

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        let trace_display = result.display_trace();
        assert!(trace_display.contains("Denied"), "Trace should show Denied");
        assert!(trace_display.contains("Test denial"), "Trace should show denial reason");
    }

    #[tokio::test]
    async fn test_access_evaluation_display_impl() {
        let mut checker = PermissionChecker::new();
        checker.add_policy(AlwaysAllowPolicy);

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        // Test Display trait
        let display_str = format!("{}", result);
        assert!(display_str.contains("GRANTED"), "Display should show GRANTED");
        assert!(display_str.contains("AlwaysAllowPolicy"), "Display should show policy name");
    }

    // ==================== EvalTrace Tests ====================

    #[test]
    fn test_eval_trace_new_creates_empty() {
        let trace = EvalTrace::new();
        assert!(trace.root().is_none(), "New trace should have no root");
        assert_eq!(
            trace.format(),
            "No evaluation trace available",
            "Empty trace should format as 'No evaluation trace available'"
        );
    }

    #[test]
    fn test_eval_trace_with_root() {
        let result = PolicyEvalResult::Granted {
            policy_type: "TestPolicy".to_string(),
            reason: Some("Test reason".to_string()),
        };
        let trace = EvalTrace::with_root(result);

        assert!(trace.root().is_some(), "Trace with root should have a root");
        let formatted = trace.format();
        assert!(formatted.contains("TestPolicy"), "Formatted trace should contain policy name");
        assert!(formatted.contains("GRANTED"), "Formatted trace should contain GRANTED");
    }

    #[test]
    fn test_eval_trace_set_root() {
        let mut trace = EvalTrace::new();
        assert!(trace.root().is_none());

        let result = PolicyEvalResult::Denied {
            policy_type: "DenyPolicy".to_string(),
            reason: "Denied for testing".to_string(),
        };
        trace.set_root(result);

        assert!(trace.root().is_some(), "After set_root, trace should have a root");
        let formatted = trace.format();
        assert!(formatted.contains("DenyPolicy"));
        assert!(formatted.contains("DENIED"));
    }

    #[test]
    fn test_eval_trace_default() {
        let trace = EvalTrace::default();
        assert!(trace.root().is_none(), "Default trace should have no root");
    }

    // ==================== PolicyEvalResult Tests ====================

    #[test]
    fn test_policy_eval_result_reason_granted() {
        let result = PolicyEvalResult::Granted {
            policy_type: "TestPolicy".to_string(),
            reason: Some("Grant reason".to_string()),
        };
        assert_eq!(result.reason(), Some("Grant reason".to_string()));

        // Test with None reason
        let result_no_reason = PolicyEvalResult::Granted {
            policy_type: "TestPolicy".to_string(),
            reason: None,
        };
        assert_eq!(result_no_reason.reason(), None);
    }

    #[test]
    fn test_policy_eval_result_reason_denied() {
        let result = PolicyEvalResult::Denied {
            policy_type: "TestPolicy".to_string(),
            reason: "Deny reason".to_string(),
        };
        assert_eq!(result.reason(), Some("Deny reason".to_string()));
    }

    #[test]
    fn test_policy_eval_result_reason_combined() {
        let result = PolicyEvalResult::Combined {
            policy_type: "CombinedPolicy".to_string(),
            operation: CombineOp::And,
            children: vec![],
            outcome: true,
        };
        assert_eq!(result.reason(), None, "Combined result should have no reason");
    }

    #[test]
    fn test_policy_eval_result_format_indentation() {
        let result = PolicyEvalResult::Granted {
            policy_type: "TestPolicy".to_string(),
            reason: Some("Test".to_string()),
        };

        let formatted_0 = result.format(0);
        let formatted_4 = result.format(4);

        assert!(formatted_0.starts_with(""), "Indent 0 should start with checkmark");
        assert!(formatted_4.starts_with(""), "Indent 4 should have 4 spaces before checkmark");
    }

    #[test]
    fn test_policy_eval_result_display() {
        let result = PolicyEvalResult::Denied {
            policy_type: "TestPolicy".to_string(),
            reason: "Test denial".to_string(),
        };

        let display_str = format!("{}", result);
        assert!(display_str.contains("TestPolicy"));
        assert!(display_str.contains("DENIED"));
        assert!(display_str.contains("Test denial"));
    }

    // ==================== CombineOp Display Tests ====================

    #[test]
    fn test_combine_op_display() {
        assert_eq!(format!("{}", CombineOp::And), "AND");
        assert_eq!(format!("{}", CombineOp::Or), "OR");
        assert_eq!(format!("{}", CombineOp::Not), "NOT");
    }

    // ==================== PermissionChecker Default Tests ====================

    #[tokio::test]
    async fn test_permission_checker_default() {
        let checker =
            PermissionChecker::<TestSubject, TestResource, TestAction, TestContext>::default();

        let subject = TestSubject {
            id: uuid::Uuid::new_v4(),
        };
        let resource = TestResource {
            id: uuid::Uuid::new_v4(),
        };

        let result = checker
            .evaluate_access(&subject, &TestAction, &resource, &TestContext)
            .await;

        // Default checker has no policies, so should deny
        assert!(!result.is_granted(), "Default checker with no policies should deny");
    }

    // ==================== SecurityRuleMetadata Tests ====================

    #[test]
    fn test_security_rule_metadata_default_values() {
        let metadata = SecurityRuleMetadata::default();

        assert_eq!(metadata.name(), None);
        assert_eq!(metadata.category(), None);
        assert_eq!(metadata.description(), None);
        assert_eq!(metadata.reference(), None);
        assert_eq!(metadata.ruleset_name(), None);
        assert_eq!(metadata.uuid(), None);
        assert_eq!(metadata.version(), None);
        assert_eq!(metadata.license(), None);
    }

    #[test]
    fn test_security_rule_metadata_new_equals_default() {
        let new_metadata = SecurityRuleMetadata::new();
        let default_metadata = SecurityRuleMetadata::default();

        assert_eq!(new_metadata, default_metadata);
    }

    #[test]
    fn test_security_rule_metadata_partial_builder() {
        // Test that we can set only some fields
        let metadata = SecurityRuleMetadata::new()
            .with_name("TestRule")
            .with_category("TestCategory");

        assert_eq!(metadata.name(), Some("TestRule"));
        assert_eq!(metadata.category(), Some("TestCategory"));
        assert_eq!(metadata.description(), None);
        assert_eq!(metadata.reference(), None);
    }

    #[tokio::test]
    async fn test_policy_default_security_rule() {
        // Test that the default security_rule implementation returns empty metadata
        let policy = AlwaysAllowPolicy;
        let metadata = Policy::<TestSubject, TestResource, TestAction, TestContext>::security_rule(&policy);

        assert_eq!(metadata, SecurityRuleMetadata::default());
    }

    // ==================== EmptyPoliciesError Tests ====================

    #[test]
    fn test_empty_policies_error_debug() {
        let error = EmptyPoliciesError("Test error message");
        let debug_str = format!("{:?}", error);
        assert!(debug_str.contains("Test error message"));
    }

    #[test]
    #[allow(clippy::clone_on_copy)] // intentionally testing both Copy and Clone
    fn test_empty_policies_error_copy_clone() {
        let error = EmptyPoliciesError("Test");
        let copied = error;
        let cloned = error.clone();

        assert_eq!(copied.0, "Test");
        assert_eq!(cloned.0, "Test");
    }
}

#[cfg(test)]
mod policy_builder_tests {
    use super::*;
    use uuid::Uuid;

    // Define simple test types
    #[derive(Debug, Clone)]
    struct TestSubject {
        pub name: String,
    }
    #[derive(Debug, Clone)]
    struct TestAction;
    #[derive(Debug, Clone)]
    struct TestResource;
    #[derive(Debug, Clone)]
    struct TestContext;

    // Test that with no predicates the builder returns a policy that always "matches"
    #[tokio::test]
    async fn test_policy_builder_allows_when_no_predicates() {
        let policy = PolicyBuilder::<TestSubject, TestResource, TestAction, TestContext>::new(
            "NoPredicatesPolicy",
        )
        .build();

        let result = policy
            .evaluate_access(
                &TestSubject { name: "Any".into() },
                &TestAction,
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(
            result.is_granted(),
            "Policy built with no predicates should allow access (default true)"
        );
    }

    // Test that a subject predicate is applied correctly.
    #[tokio::test]
    async fn test_policy_builder_with_subject_predicate() {
        let policy = PolicyBuilder::<TestSubject, TestResource, TestAction, TestContext>::new(
            "SubjectPolicy",
        )
        .subjects(|s: &TestSubject| s.name == "Alice")
        .build();

        // Should allow if the subject's name is "Alice"
        let result1 = policy
            .evaluate_access(
                &TestSubject {
                    name: "Alice".into(),
                },
                &TestAction,
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(
            result1.is_granted(),
            "Policy should allow access for subject 'Alice'"
        );

        // Otherwise, it should deny
        let result2 = policy
            .evaluate_access(
                &TestSubject { name: "Bob".into() },
                &TestAction,
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(
            !result2.is_granted(),
            "Policy should deny access for subject not named 'Alice'"
        );
    }

    // Test that setting the effect to Deny overrides an otherwise matching predicate.
    #[tokio::test]
    async fn test_policy_builder_effect_deny() {
        let policy =
            PolicyBuilder::<TestSubject, TestResource, TestAction, TestContext>::new("DenyPolicy")
                .effect(Effect::Deny)
                .build();

        // Even though no predicate fails (so predicate returns true),
        // the effect should result in a Denied outcome.
        let result = policy
            .evaluate_access(
                &TestSubject {
                    name: "Anyone".into(),
                },
                &TestAction,
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(
            !result.is_granted(),
            "Policy with effect Deny should result in denial even if the predicate passes"
        );
    }

    // Test that extra conditions (combining multiple inputs) work correctly.
    #[tokio::test]
    async fn test_policy_builder_with_extra_condition() {
        #[derive(Debug, Clone)]
        struct ExtendedSubject {
            pub id: Uuid,
            pub name: String,
        }
        #[derive(Debug, Clone)]
        struct ExtendedResource {
            pub owner_id: Uuid,
        }
        #[derive(Debug, Clone)]
        struct ExtendedAction;
        #[derive(Debug, Clone)]
        struct ExtendedContext;

        // Build a policy that checks:
        //   1. Subject's name is "Alice"
        //   2. And that subject.id == resource.owner_id (via extra condition)
        let subject_id = Uuid::new_v4();
        let policy = PolicyBuilder::<
            ExtendedSubject,
            ExtendedResource,
            ExtendedAction,
            ExtendedContext,
        >::new("AliceOwnerPolicy")
        .subjects(|s: &ExtendedSubject| s.name == "Alice")
        .when(|s, _a, r, _c| s.id == r.owner_id)
        .build();

        // Case where both conditions are met.
        let result1 = policy
            .evaluate_access(
                &ExtendedSubject {
                    id: subject_id,
                    name: "Alice".into(),
                },
                &ExtendedAction,
                &ExtendedResource {
                    owner_id: subject_id,
                },
                &ExtendedContext,
            )
            .await;
        assert!(
            result1.is_granted(),
            "Policy should allow access when conditions are met"
        );

        // Case where extra condition fails (different id)
        let result2 = policy
            .evaluate_access(
                &ExtendedSubject {
                    id: subject_id,
                    name: "Alice".into(),
                },
                &ExtendedAction,
                &ExtendedResource {
                    owner_id: Uuid::new_v4(),
                },
                &ExtendedContext,
            )
            .await;
        assert!(
            !result2.is_granted(),
            "Policy should deny access when extra condition fails"
        );
    }

    // Test action predicate
    #[tokio::test]
    async fn test_policy_builder_with_action_predicate() {
        #[derive(Debug, Clone)]
        struct ActionType {
            pub name: String,
        }

        let policy =
            PolicyBuilder::<TestSubject, TestResource, ActionType, TestContext>::new("ActionPolicy")
                .actions(|a: &ActionType| a.name == "read")
                .build();

        // Should allow for "read" action
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &ActionType { name: "read".into() },
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(result.is_granted(), "Policy should allow 'read' action");

        // Should deny for "write" action
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &ActionType { name: "write".into() },
                &TestResource,
                &TestContext,
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny 'write' action");
    }

    // Test resource predicate
    #[tokio::test]
    async fn test_policy_builder_with_resource_predicate() {
        #[derive(Debug, Clone)]
        struct ResourceType {
            pub public: bool,
        }

        let policy = PolicyBuilder::<TestSubject, ResourceType, TestAction, TestContext>::new(
            "ResourcePolicy",
        )
        .resources(|r: &ResourceType| r.public)
        .build();

        // Should allow access to public resource
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &TestAction,
                &ResourceType { public: true },
                &TestContext,
            )
            .await;
        assert!(result.is_granted(), "Policy should allow public resource");

        // Should deny access to private resource
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &TestAction,
                &ResourceType { public: false },
                &TestContext,
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny private resource");
    }

    // Test context predicate
    #[tokio::test]
    async fn test_policy_builder_with_context_predicate() {
        #[derive(Debug, Clone)]
        struct RequestContext {
            pub is_internal: bool,
        }

        let policy = PolicyBuilder::<TestSubject, TestResource, TestAction, RequestContext>::new(
            "ContextPolicy",
        )
        .context(|c: &RequestContext| c.is_internal)
        .build();

        // Should allow for internal requests
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &TestAction,
                &TestResource,
                &RequestContext { is_internal: true },
            )
            .await;
        assert!(result.is_granted(), "Policy should allow internal requests");

        // Should deny for external requests
        let result = policy
            .evaluate_access(
                &TestSubject { name: "Anyone".into() },
                &TestAction,
                &TestResource,
                &RequestContext { is_internal: false },
            )
            .await;
        assert!(
            !result.is_granted(),
            "Policy should deny external requests"
        );
    }

    // Test combining all predicates
    #[tokio::test]
    async fn test_policy_builder_with_all_predicates_combined() {
        #[derive(Debug, Clone)]
        struct FullSubject {
            pub role: String,
        }
        #[derive(Debug, Clone)]
        struct FullAction {
            pub name: String,
        }
        #[derive(Debug, Clone)]
        struct FullResource {
            pub category: String,
        }
        #[derive(Debug, Clone)]
        struct FullContext {
            pub time_of_day: String,
        }

        // Policy: admin can read documents during business hours
        let policy =
            PolicyBuilder::<FullSubject, FullResource, FullAction, FullContext>::new("FullPolicy")
                .subjects(|s: &FullSubject| s.role == "admin")
                .actions(|a: &FullAction| a.name == "read")
                .resources(|r: &FullResource| r.category == "document")
                .context(|c: &FullContext| c.time_of_day == "business_hours")
                .build();

        // All conditions met - should allow
        let result = policy
            .evaluate_access(
                &FullSubject {
                    role: "admin".into(),
                },
                &FullAction { name: "read".into() },
                &FullResource {
                    category: "document".into(),
                },
                &FullContext {
                    time_of_day: "business_hours".into(),
                },
            )
            .await;
        assert!(
            result.is_granted(),
            "Policy should allow when all conditions are met"
        );

        // Wrong role - should deny
        let result = policy
            .evaluate_access(
                &FullSubject {
                    role: "user".into(),
                },
                &FullAction { name: "read".into() },
                &FullResource {
                    category: "document".into(),
                },
                &FullContext {
                    time_of_day: "business_hours".into(),
                },
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny wrong role");

        // Wrong action - should deny
        let result = policy
            .evaluate_access(
                &FullSubject {
                    role: "admin".into(),
                },
                &FullAction {
                    name: "write".into(),
                },
                &FullResource {
                    category: "document".into(),
                },
                &FullContext {
                    time_of_day: "business_hours".into(),
                },
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny wrong action");

        // Wrong resource - should deny
        let result = policy
            .evaluate_access(
                &FullSubject {
                    role: "admin".into(),
                },
                &FullAction { name: "read".into() },
                &FullResource {
                    category: "video".into(),
                },
                &FullContext {
                    time_of_day: "business_hours".into(),
                },
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny wrong resource");

        // Wrong context - should deny
        let result = policy
            .evaluate_access(
                &FullSubject {
                    role: "admin".into(),
                },
                &FullAction { name: "read".into() },
                &FullResource {
                    category: "document".into(),
                },
                &FullContext {
                    time_of_day: "after_hours".into(),
                },
            )
            .await;
        assert!(!result.is_granted(), "Policy should deny wrong context");
    }
}