larastvel-macros 0.2.2

Larastvel procedural macros
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
use proc_macro::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, Ident, ImplItem, ItemImpl, ItemStruct, ItemTrait, Lit, LitStr,
};

fn snake_to_pascal(s: &str) -> String {
    s.split('_')
        .map(|w| {
            let mut c = w.chars();
            match c.next() {
                None => String::new(),
                Some(f) => f.to_uppercase().to_string() + c.as_str(),
            }
        })
        .collect()
}

fn resource_name_from_ident(name: &syn::Ident) -> String {
    let s = name.to_string();
    s.strip_suffix("Controller").unwrap_or(&s).to_lowercase()
}

// ---------------------------------------------------------------------------
// Derive: Resource
// ---------------------------------------------------------------------------

#[proc_macro_derive(Resource, attributes(resource))]
pub fn derive_resource(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::DeriveInput);
    let name = &input.ident;

    let resource_name = resource_name_from_ident(name);

    let expanded = quote! {
        impl larastvel_core::routing::ResourceController for #name {
            const RESOURCE_NAME: &'static str = #resource_name;
        }

        impl #name {
            pub fn register_routes(
                registrar: &larastvel_core::routing::Registrar,
            ) {
                let __name =
                    <Self as larastvel_core::routing::ResourceController>::RESOURCE_NAME;

                registrar.get(
                    &format!("/{}", __name),
                    Self::__resource_index,
                );
                registrar.get(
                    &format!("/{}/create", __name),
                    Self::__resource_create,
                );
                registrar.post(
                    &format!("/{}", __name),
                    Self::__resource_store,
                );
                registrar.get(
                    &format!("/{}/{{id}}", __name),
                    Self::__resource_show,
                );
                registrar.get(
                    &format!("/{}/{{id}}/edit", __name),
                    Self::__resource_edit,
                );
                registrar.put(
                    &format!("/{}/{{id}}", __name),
                    Self::__resource_update,
                );
                registrar.delete(
                    &format!("/{}/{{id}}", __name),
                    Self::__resource_destroy,
                );
            }

            async fn __resource_index(
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::index().await
            }

            async fn __resource_create(
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::create().await
            }

            async fn __resource_store(
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::store().await
            }

            async fn __resource_show(
                larastvel_core::axum::extract::Path(id):
                    larastvel_core::axum::extract::Path<String>,
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::show(id).await
            }

            async fn __resource_edit(
                larastvel_core::axum::extract::Path(id):
                    larastvel_core::axum::extract::Path<String>,
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::edit(id).await
            }

            async fn __resource_update(
                larastvel_core::axum::extract::Path(id):
                    larastvel_core::axum::extract::Path<String>,
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::update(id).await
            }

            async fn __resource_destroy(
                larastvel_core::axum::extract::Path(id):
                    larastvel_core::axum::extract::Path<String>,
            ) -> larastvel_core::axum::response::Response {
                <Self as larastvel_core::routing::ResourceController>::destroy(id).await
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[controller]
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn controller(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;

    let expanded = quote! {
        #input

        impl #name {
            pub fn register_routes(
                _registrar: &larastvel_core::routing::Registrar,
            ) {
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Helper: string literal argument parser
// ---------------------------------------------------------------------------

struct UriArg {
    uri: String,
}

impl Parse for UriArg {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lit: Lit = input.parse()?;
        match lit {
            Lit::Str(s) => Ok(UriArg { uri: s.value() }),
            _ => Err(syn::Error::new(lit.span(), "expected string literal")),
        }
    }
}

// ---------------------------------------------------------------------------
// Marker attribute macros: #[get], #[post], #[put], #[patch], #[delete], #[ws]
// These are identity transforms.  The #[route] macro on the enclosing impl
// block reads them out of the raw attribute list.
// ---------------------------------------------------------------------------

/// Marks a handler function for GET requests. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn get(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function for POST requests. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn post(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function for PUT requests. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn put(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function for PATCH requests. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn patch(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function for DELETE requests. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn delete(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function for WebSocket upgrades. Must be used inside a `#[route]` impl block.
#[proc_macro_attribute]
pub fn ws(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// Marks a handler function with middleware. Must be used inside a `#[route]` impl block.
///
/// Accepts one or more middleware names:
/// ```ignore
/// #[middleware("auth")]
/// #[middleware("auth", "admin")]
/// ```
#[proc_macro_attribute]
pub fn middleware(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

// ---------------------------------------------------------------------------
// Parser for middleware arguments: one or more comma-separated string literals.
// ---------------------------------------------------------------------------

struct MiddlewareArgs {
    names: Vec<String>,
}

impl Parse for MiddlewareArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut names = Vec::new();
        while !input.is_empty() {
            let lit: Lit = input.parse()?;
            match lit {
                Lit::Str(s) => names.push(s.value()),
                _ => return Err(syn::Error::new(lit.span(), "expected string literal")),
            }
            if !input.is_empty() {
                input.parse::<syn::Token![,]>()?;
            }
        }
        Ok(MiddlewareArgs { names })
    }
}

// ---------------------------------------------------------------------------
// Attribute: #[listener(EventType)]
//
// Converts an async function into a zero-sized Listener struct that
// implements the `Listener<EventType>` trait and provides a `listen()`
// helper to register it with `EventService`.
//
// Usage:
//   #[listener(OrderShipped)]
//   async fn send_notification(event: OrderShipped) {
//       tracing::info!("Order {} shipped", event.order_id);
//   }
//
// Expands to:
//   struct SendNotificationListener;
//
//   #[async_trait]
//   impl listener<OrderShipped> for SendNotificationListener {
//       async fn handle(&self, event: OrderShipped) { ... }
//   }
//
//   impl SendNotificationListener {
//       fn listen() {
//           EventService::listen::<OrderShipped, Self>(Self);
//       }
//   }
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn listener(attr: TokenStream, item: TokenStream) -> TokenStream {
    let event_ty: syn::Type = parse_macro_input!(attr as syn::Type);
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[listener] requires async fn")
            .to_compile_error()
            .into();
    }

    let fn_name = &func.sig.ident;
    let struct_name_str = snake_to_pascal(&fn_name.to_string()) + "Listener";
    let struct_name = syn::Ident::new(&struct_name_str, fn_name.span());
    let vis = &func.vis;
    let body = &func.block;
    let params = &func.sig.inputs;

    let expanded = quote! {
        #vis struct #struct_name;

        #[larastvel_core::async_trait]
        impl larastvel_core::events::Listener<#event_ty> for #struct_name {
            async fn handle(&self, #params) {
                #body
            }
        }

        impl #struct_name {
            pub fn listen() {
                larastvel_core::events::EventService::listen::<#event_ty, Self>(Self);
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[job]
//
// Converts an async function into a queue job struct that implements
// `ShouldQueue`.  The function parameters become struct fields, and the
// generated struct provides `new()`, `dispatch()`, and `name()` methods.
//
// Usage:
//   #[job]
//   async fn process_podcast(podcast_id: i32) -> Result<(), JobError> {
//       tracing::info!("Processing podcast {}", podcast_id);
//       Ok(())
//   }
//
// Expands to:
//   #[derive(Debug)]
//   pub struct ProcessPodcastJob {
//       pub podcast_id: i32,
//   }
//
//   impl ProcessPodcastJob {
//       pub fn new(podcast_id: i32) -> Self { ... }
//       pub async fn dispatch(self) -> Result<(), JobError> { ... }
//   }
//
//   #[async_trait]
//   impl ShouldQueue for ProcessPodcastJob {
//       fn name(&self) -> &str { "process_podcast" }
//       async fn handle(&self) -> Result<(), JobError> {
//           __process_podcast_inner(self.podcast_id).await
//       }
//   }
//
//   async fn __process_podcast_inner(podcast_id: i32) -> Result<(), JobError> { ... }
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Attribute: #[job(tries = 5, backoff = 10, timeout = 30, fail_on_timeout, delay = 60)]
//
// Generates a `*Job` struct implementing `ShouldQueue` from an async fn, with
// optional Laravel-style queue attributes: `tries`, `backoff`, `timeout`,
// `fail_on_timeout`, and `delay` (Laravel's `#[Delay]` attribute).
// ---------------------------------------------------------------------------

#[derive(Default)]
struct JobAttrs {
    tries: Option<u64>,
    backoff: Option<u64>,
    timeout: Option<u64>,
    fail_on_timeout: bool,
    delay: Option<u64>,
}

impl Parse for JobAttrs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut attrs = JobAttrs::default();
        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            let name = ident.to_string();
            match name.as_str() {
                "fail_on_timeout" => attrs.fail_on_timeout = true,
                "tries" | "backoff" | "timeout" | "delay" => {
                    input.parse::<syn::Token![=]>()?;
                    let lit: syn::LitInt = input.parse()?;
                    let value = lit.base10_parse::<u64>().map_err(|_| {
                        syn::Error::new(lit.span(), format!("#[job] {name} must be an integer"))
                    })?;
                    match name.as_str() {
                        "tries" => attrs.tries = Some(value),
                        "backoff" => attrs.backoff = Some(value),
                        "delay" => attrs.delay = Some(value),
                        _ => attrs.timeout = Some(value),
                    }
                }
                _ => {
                    return Err(syn::Error::new(
                        ident.span(),
                        format!("unknown #[job] attribute: {name}"),
                    ))
                }
            }
            if input.is_empty() {
                break;
            }
            input.parse::<syn::Token![,]>()?;
        }
        Ok(attrs)
    }
}

#[proc_macro_attribute]
pub fn job(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attrs = parse_macro_input!(attr as JobAttrs);
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[job] requires async fn")
            .to_compile_error()
            .into();
    }

    let fn_name = &func.sig.ident;
    let fn_name_str = fn_name.to_string();
    // Strip trailing "_job" suffix so `fn simple_job` yields struct `SimpleJob`, not `SimpleJobJob`.
    let stem = if fn_name_str.ends_with("_job") && fn_name_str.len() > 4 {
        &fn_name_str[..fn_name_str.len() - 4]
    } else {
        &fn_name_str
    };
    let struct_name_str = snake_to_pascal(stem) + "Job";
    let struct_name = syn::Ident::new(&struct_name_str, fn_name.span());
    let inner_fn_name = syn::Ident::new(&format!("__{}_inner", fn_name_str), fn_name.span());
    let vis = &func.vis;
    let output_ty = &func.sig.output;
    let body = &func.block;

    // Parse function params into struct fields.
    let mut field_tokens = Vec::new();
    let mut new_param_tokens = Vec::new();
    let mut field_assignments = Vec::new();
    let mut dispatch_args = Vec::new();
    let mut handle_args = Vec::new();

    for arg in &func.sig.inputs {
        match arg {
            syn::FnArg::Typed(pat_type) => {
                let pat = &pat_type.pat;
                let ty = &pat_type.ty;
                field_tokens.push(quote! { pub #pat: #ty });
                new_param_tokens.push(quote! { #pat: #ty });
                field_assignments.push(quote! { #pat });
                // In dispatch(self), self is owned so we can move fields out.
                dispatch_args.push(quote! { self.#pat });
                // In handle(&self), we must clone since we only have &self.
                handle_args.push(quote! { self.#pat.clone() });
            }
            syn::FnArg::Receiver(_) => {
                return syn::Error::new(arg.span(), "#[job] cannot be used on methods with self")
                    .to_compile_error()
                    .into();
            }
        }
    }

    let tries = match attrs.tries {
        Some(t) => quote! { Some(#t) },
        None => quote! { None },
    };
    let backoff = match attrs.backoff {
        Some(b) => quote! { Some(#b) },
        None => quote! { None },
    };
    let timeout = match attrs.timeout {
        Some(t) => quote! { Some(#t) },
        None => quote! { None },
    };
    let fail_on_timeout = if attrs.fail_on_timeout {
        quote! { true }
    } else {
        quote! { false }
    };
    let delay = match attrs.delay {
        Some(d) => quote! { Some(#d) },
        None => quote! { None },
    };

    let expanded = quote! {
        #[derive(Debug)]
        #vis struct #struct_name {
            #(#field_tokens,)*
        }

        impl #struct_name {
            pub fn new(#(#new_param_tokens),*) -> Self {
                Self {
                    #(#field_assignments,)*
                }
            }

            pub async fn dispatch(self) -> Result<(), larastvel_core::queue::JobError> {
                #inner_fn_name(#(#dispatch_args),*).await
            }
        }

        #[larastvel_core::async_trait]
        impl larastvel_core::queue::ShouldQueue for #struct_name {
            fn name(&self) -> &str {
                #fn_name_str
            }

            fn max_attempts(&self) -> Option<u64> {
                #tries
            }

            fn backoff_seconds(&self) -> Option<u64> {
                #backoff
            }

            fn timeout_seconds(&self) -> Option<u64> {
                #timeout
            }

            fn fail_on_timeout(&self) -> bool {
                #fail_on_timeout
            }

            fn delay_seconds(&self) -> Option<u64> {
                #delay
            }

            async fn handle(&self) -> Result<(), larastvel_core::queue::JobError> {
                #inner_fn_name(#(#handle_args),*).await
            }
        }

        #[allow(dead_code)]
        async fn #inner_fn_name(#(#new_param_tokens),*) #output_ty {
            #body
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[queued_listener(EventType)]
//
// Like `#[listener]` but dispatches the handler as a background job instead
// of running synchronously.  Generates both a `*Listener` struct (registered
// with EventService) and a `*Job` struct (implements ShouldQueue).
//
// Usage:
//   #[queued_listener(OrderShipped)]
//   async fn handle_order_shipped(event: OrderShipped) -> Result<(), JobError> {
//       tracing::info!("Processing order {}", event.order_id);
//       Ok(())
//   }
//
// This registers a listener that, on each event, dispatches a
// `HandleOrderShippedJob` to the default queue.
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn queued_listener(attr: TokenStream, item: TokenStream) -> TokenStream {
    let event_ty: syn::Type = parse_macro_input!(attr as syn::Type);
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[queued_listener] requires async fn")
            .to_compile_error()
            .into();
    }

    let fn_name = &func.sig.ident;
    let fn_name_str = fn_name.to_string();

    // Strip trailing "_listener" for a cleaner struct name.
    let stem = if fn_name_str.ends_with("_listener") && fn_name_str.len() > 10 {
        &fn_name_str[..fn_name_str.len() - 9]
    } else {
        &fn_name_str
    };
    // Strip trailing "_handler" too.
    let stem = if stem.ends_with("_handler") && stem.len() > 8 {
        &stem[..stem.len() - 8]
    } else {
        stem
    };

    let struct_stem = snake_to_pascal(stem);
    let job_struct_name = syn::Ident::new(&(struct_stem.clone() + "Job"), fn_name.span());
    let listener_struct_name = syn::Ident::new(&(struct_stem + "Listener"), fn_name.span());
    let inner_fn_name = syn::Ident::new(&format!("__{}_inner", fn_name_str), fn_name.span());
    let vis = &func.vis;
    let output = &func.sig.output;
    let body = &func.block;

    // Extract the event parameter.
    let event_param = func.sig.inputs.first().and_then(|arg| match arg {
        syn::FnArg::Typed(pat_type) => Some((pat_type.pat.clone(), pat_type.ty.clone())),
        _ => None,
    });

    let Some((event_pat, event_ty_inner)) = event_param else {
        return syn::Error::new(
            func.sig.span(),
            "#[queued_listener] requires exactly one parameter: the event",
        )
        .to_compile_error()
        .into();
    };

    let expanded = quote! {
        // --- Job struct ---
        #[derive(Debug)]
        #vis struct #job_struct_name {
            pub #event_pat: #event_ty_inner,
        }

        impl #job_struct_name {
            pub fn new(#event_pat: #event_ty_inner) -> Self {
                Self { #event_pat }
            }

            pub async fn dispatch(self) -> Result<(), larastvel_core::queue::JobError> {
                #inner_fn_name(self.#event_pat).await
            }
        }

        #[larastvel_core::async_trait]
        impl larastvel_core::queue::ShouldQueue for #job_struct_name {
            fn name(&self) -> &str {
                #fn_name_str
            }

            async fn handle(&self) -> Result<(), larastvel_core::queue::JobError> {
                #inner_fn_name(self.#event_pat.clone()).await
            }
        }

        #[allow(dead_code)]
        async fn #inner_fn_name(#event_pat: #event_ty_inner) #output {
            #body
        }

        // --- Listener struct ---
        #vis struct #listener_struct_name;

        #[larastvel_core::async_trait]
        impl larastvel_core::events::Listener<#event_ty> for #listener_struct_name {
            async fn handle(&self, #event_pat: #event_ty_inner) {
                if let Err(e) = #job_struct_name::new(#event_pat).dispatch().await {
                    tracing::error!("Queued listener failed: {e}");
                }
            }
        }

        impl #listener_struct_name {
            pub fn listen() {
                larastvel_core::events::EventService::listen::<#event_ty, Self>(Self);
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[can("ability")]
//
// Adds authorization checking to an async handler function.
//
// Prepends `AuthenticatedUser` and `Extension<Gate>` extractor parameters
// and wraps the body with an ability check.  The function return type is
// changed to `axum::response::Response`.
//
// Usage:
//   #[can("admin")]
//   async fn dashboard(Extension(state): Extension<AppState>) -> impl IntoResponse {
//       Html("<h1>Admin</h1>")
//   }
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn can(attr: TokenStream, item: TokenStream) -> TokenStream {
    let parsed = parse_macro_input!(attr as UriArg);
    let ability = parsed.uri;
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[can] requires async fn")
            .to_compile_error()
            .into();
    }

    let vis = &func.vis;
    let name = &func.sig.ident;
    let inputs = &func.sig.inputs;
    let body = &func.block;

    for input in inputs {
        if let syn::FnArg::Receiver(_) = input {
            return syn::Error::new(input.span(), "#[can] cannot be used on methods with self")
                .to_compile_error()
                .into();
        }
    }

    let expanded = quote! {
        #vis async fn #name(
            __larastvel_auth: larastvel_core::auth::AuthenticatedUser,
            __larastvel_gate: larastvel_core::axum::Extension<larastvel_core::auth::Gate>,
            #inputs
        ) -> larastvel_core::axum::response::Response {
            if let Err(__larastvel_e) = larastvel_core::auth::check_ability(#ability, &__larastvel_auth, &__larastvel_gate.0).await {
                return __larastvel_e.into_response();
            }
            larastvel_core::axum::response::IntoResponse::into_response(#body)
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[validate(rules_expr)]
//
// Validates a JSON request body before the handler runs.
//
// The attribute argument must be an expression that evaluates to
// `Vec<(&str, Vec<Rule>)>`.  The handler must have a `Json<Value>`
// parameter (typically `Json(body): Json<Value>`).
//
// The return type is changed to `axum::response::Response`.
//
// Usage:
//   #[validate(vec![("email", vec![Rule::required(), Rule::email()])])]
//   async fn store(Json(body): Json<Value>) -> impl IntoResponse {
//       Json(json!({"ok": true}))
//   }
// ---------------------------------------------------------------------------

/// Extracts the binding name from a pattern like `Json(body)` or `body`.
fn extract_json_binding(pat: &syn::Pat) -> Option<proc_macro2::TokenStream> {
    match pat {
        // `Json(body)` — body IS the inner Value
        syn::Pat::TupleStruct(ps) if ps.elems.len() == 1 => {
            if let syn::Pat::Ident(inner) = &ps.elems[0] {
                let id = &inner.ident;
                return Some(quote! { #id });
            }
            None
        }
        // `Json { body }` — body IS the inner Value
        syn::Pat::Struct(ps) => ps.fields.first().and_then(|f| match &*f.pat {
            syn::Pat::Ident(ident) => {
                let id = &ident.ident;
                Some(quote! { #id })
            }
            _ => None,
        }),
        // `body: Json<Value>` — body IS the Json<Value> struct, need .0
        syn::Pat::Ident(pi) => {
            let id = &pi.ident;
            Some(quote! { #id . 0 })
        }
        _ => None,
    }
}

#[proc_macro_attribute]
pub fn validate(attr: TokenStream, item: TokenStream) -> TokenStream {
    let rules_expr = proc_macro2::TokenStream::from(attr);
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[validate] requires async fn")
            .to_compile_error()
            .into();
    }

    let vis = &func.vis;
    let name = &func.sig.ident;
    let inputs = &func.sig.inputs;
    let body = &func.block;

    for input in inputs {
        if let syn::FnArg::Receiver(_) = input {
            return syn::Error::new(
                input.span(),
                "#[validate] cannot be used on methods with self",
            )
            .to_compile_error()
            .into();
        }
    }

    // Find the Json<Value> binding in the handler parameters.
    let body_access = inputs
        .iter()
        .find_map(|arg| {
            if let syn::FnArg::Typed(pat_type) = arg {
                let ty_str = quote! { #pat_type.ty }.to_string();
                if ty_str.contains("Json") && ty_str.contains("Value") {
                    return extract_json_binding(pat_type.pat.as_ref());
                }
            }
            None
        })
        .unwrap_or_else(|| {
            // Fallback: create a synthetic accessor for "__body.0"
            quote! { __body . 0 }
        });

    let expanded = quote! {
        #vis async fn #name(
            #inputs
        ) -> larastvel_core::axum::response::Response {
            use std::collections::HashMap;

            let __larastvel_body: &serde_json::Value = &(#body_access);
            let __data: HashMap<String, serde_json::Value> = match __larastvel_body.as_object() {
                Some(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
                None => {
                    let mut __errors = larastvel_core::validation::ValidationErrors::new();
                    __errors.add("_", "Request body must be a JSON object.");
                    return __errors.into_response();
                }
            };

            let __rules = #rules_expr;

            if let Err(__errors) =
                larastvel_core::validation::validate_async(&__data, __rules).await
            {
                return __errors.into_response();
            }

            larastvel_core::axum::response::IntoResponse::into_response(#body)
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[validated_query(rules_expr)]
//
// Validates query-string parameters before the handler runs.
//
// The attribute argument must be an expression that evaluates to
// `Vec<(&str, Vec<Rule>)>`.  The handler must have a `Query<HashMap<String,
// String>>` parameter (typically `Query(params): Query<HashMap<String, String>>`).
//
// The return type is changed to `axum::response::Response`.
//
// Usage:
//   #[validated_query(vec![("page", vec![required(), numeric()])])]
//   async fn list(Query(params): Query<HashMap<String, String>>) -> impl IntoResponse {
//       Json(json!({"page": params.get("page")}))
//   }
// ---------------------------------------------------------------------------

/// Extracts the binding name from a pattern like `Query(params)` or `params`.
fn extract_query_binding(pat: &syn::Pat) -> Option<proc_macro2::TokenStream> {
    // Same logic as extract_json_binding — patterns are identical.
    extract_json_binding(pat)
}

#[proc_macro_attribute]
pub fn validated_query(attr: TokenStream, item: TokenStream) -> TokenStream {
    let rules_expr = proc_macro2::TokenStream::from(attr);
    let func = parse_macro_input!(item as syn::ItemFn);

    if func.sig.asyncness.is_none() {
        return syn::Error::new(func.sig.span(), "#[validated_query] requires async fn")
            .to_compile_error()
            .into();
    }

    let vis = &func.vis;
    let name = &func.sig.ident;
    let inputs = &func.sig.inputs;
    let body = &func.block;

    for input in inputs {
        if let syn::FnArg::Receiver(_) = input {
            return syn::Error::new(
                input.span(),
                "#[validated_query] cannot be used on methods with self",
            )
            .to_compile_error()
            .into();
        }
    }

    // Find the Query<…> binding in the handler parameters.
    let body_access = inputs
        .iter()
        .find_map(|arg| {
            if let syn::FnArg::Typed(pat_type) = arg {
                let ty_str = quote! { #pat_type.ty }.to_string();
                if ty_str.contains("Query") {
                    return extract_query_binding(pat_type.pat.as_ref());
                }
            }
            None
        })
        .unwrap_or_else(|| {
            quote! { __params }
        });

    let expanded = quote! {
        #vis async fn #name(
            #inputs
        ) -> larastvel_core::axum::response::Response {
            use std::collections::HashMap;

            let __raw: &HashMap<String, String> = &(#body_access);
            let __data: HashMap<String, serde_json::Value> = __raw
                .iter()
                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                .collect();

            let __rules = #rules_expr;

            if let Err(__errors) =
                larastvel_core::validation::validate_async(&__data, __rules).await
            {
                return __errors.into_response();
            }

            larastvel_core::axum::response::IntoResponse::into_response(#body)
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[table("name")] / #[table("name", route_key = "column")]
//
// Converts a plain struct into a full SeaORM entity, eliminating the
// boilerplate of `DeriveEntityModel`, `Relation`, `ActiveModelBehavior`,
// and the `DbModel` wrapper.
//
// Usage:
//   #[table("users")]
//   pub struct User {
//       #[sea_orm(primary_key)]
//       pub id: i32,
//       pub name: String,
//       pub email: String,
//       pub password: String,
//       pub email_verified_at: Option<DateTime>,
//       pub created_at: DateTime,
//       pub updated_at: DateTime,
//   }
//
// Expands to a `__table_User` inner module containing a Model struct
// with `DeriveEntityModel`, a `Relation` enum, `ActiveModelBehavior`,
// and re-exports `Model`, `Entity`, `ActiveModel`, `Column`.
// The original struct name is kept as a `DbModel` wrapper.
//
// Field-level `#[sea_orm(…)]` attributes are passed through directly
// to `DeriveEntityModel` – all SeaORM options (primary_key,
// auto_increment, unique, default_value, indexed, column_type, …)
// are supported.
//
// The optional `route_key = "column"` option (Laravel 13.21's
// `#[RouteKey('slug')]` attribute) selects the column used by implicit
// route model binding (`ModelPath`); without it, binding resolves by
// primary key.
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn table(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input: syn::ItemStruct = syn::parse_macro_input!(item as syn::ItemStruct);

    use syn::parse::Parser as _;

    let parsed = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
        .parse(attr)
        .unwrap_or_else(|e| {
            panic!(
                "#[table] expects `\"table_name\"` or `\"table_name\", route_key = \"column\"`: {}",
                e
            )
        });
    let mut iter = parsed.iter();
    let table_name: String = match iter.next() {
        Some(syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        })) => s.value(),
        _ => panic!("#[table] expects a table name string as the first argument"),
    };
    let mut route_key: Option<String> = None;
    for option in iter {
        if let syn::Expr::Assign(syn::ExprAssign { left, right, .. }) = option {
            if let (
                syn::Expr::Path(p),
                syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(s),
                    ..
                }),
            ) = (&**left, &**right)
            {
                if p.path.is_ident("route_key") {
                    route_key = Some(s.value());
                    continue;
                }
            }
        }
        panic!("#[table] unknown option (expected `route_key = \"column\"`)");
    }

    let name = &input.ident;
    let vis = &input.vis;
    let fields = &input.fields;
    let table = table_name;
    let mod_name = syn::Ident::new(&format!("__table_{}", name), name.span());

    // route_key = "slug" → Column variant ident (PascalCase of the column).
    let route_key_method = match &route_key {
        Some(column) => {
            let variant = column_variant_ident(column);
            quote! {
                fn route_key() -> Option<&'static str> {
                    Some(#column)
                }

                async fn find_by_route_key(
                    db: &sea_orm::DatabaseConnection,
                    value: &str,
                ) -> Result<Option<Self>, sea_orm::DbErr> {
                    Entity::find()
                        .filter(Column::#variant.eq(value.to_string()))
                        .one(db)
                        .await
                }
            }
        }
        None => quote! {},
    };

    let expanded = quote! {
        #[doc(hidden)]
        #[allow(non_snake_case)]
        mod #mod_name {
            use larastvel_core::sea_orm;
            use sea_orm::entity::prelude::*;

            #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
            #[sea_orm(table_name = #table)]
            pub struct Model #fields

            #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
            pub enum Relation {}

            impl ActiveModelBehavior for ActiveModel {}

            #[larastvel_core::async_trait]
            impl larastvel_core::routing::RouteKey for Model {
                #route_key_method
            }
        }

        pub use #mod_name::Model;
        pub use #mod_name::Entity;
        pub use #mod_name::ActiveModel;
        pub use #mod_name::Column;

        #vis struct #name;

        impl larastvel_core::models::DbModel for #name {
            type Entity = Entity;
        }
    };

    TokenStream::from(expanded)
}

/// `"user_id"` → `UserId` — the SeaORM column variant name for a column.
fn column_variant_ident(column: &str) -> syn::Ident {
    let pascal: String = column
        .split('_')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect();
    if pascal.is_empty() {
        panic!("#[table] route_key column name must not be empty");
    }
    syn::Ident::new(&pascal, proc_macro2::Span::call_site())
}

// ---------------------------------------------------------------------------
// Attribute: #[scope]
//
// Converts a query-scope function into a static method on a DbModel wrapper
// struct (designed for use inside an `impl Model` block).
//
// The first parameter (the SeaORM Select builder) is removed from the
// public signature; the generated method internally calls `Self::query()`
// and passes it as that parameter.
//
// The function name may optionally start with `scope_` — the prefix is
// stripped for the public name (matching Laravel conventions).
//
// Usage:
//   impl User {
//       #[scope]
//       fn popular(query: Select<Entity>, min_likes: i64) -> Select<Entity> {
//           query.filter(Column::Likes.gte(min_likes))
//       }
//   }
//
// Expands to:
//   impl User {
//       pub fn popular(min_likes: i64) -> Select<Entity> {
//           let query = Self::query();
//           query.filter(Column::Likes.gte(min_likes))
//       }
//   }
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn scope(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let func = parse_macro_input!(item as syn::ItemFn);

    // Reject methods that take self.
    for arg in &func.sig.inputs {
        if matches!(arg, syn::FnArg::Receiver(_)) {
            return syn::Error::new(
                func.sig.span(),
                "#[scope] cannot be used on methods with `self`",
            )
            .to_compile_error()
            .into();
        }
    }

    // Require at least one parameter (the query).
    if func.sig.inputs.is_empty() {
        return syn::Error::new(
            func.sig.span(),
            "#[scope] requires at least one parameter (the SeaORM query)",
        )
        .to_compile_error()
        .into();
    }

    let fn_name = &func.sig.ident;
    let name_str = fn_name.to_string();

    // Strip optional "scope_" prefix (Laravel convention).
    let public_name_str = name_str.strip_prefix("scope_").unwrap_or(&name_str);
    let public_name = syn::Ident::new(public_name_str, fn_name.span());

    let vis = &func.vis;
    let output_ty = &func.sig.output;

    // Name of the first parameter (the query builder).
    let first_pat = match func.sig.inputs.first().unwrap() {
        syn::FnArg::Typed(pat_type) => pat_type.pat.as_ref().clone(),
        _ => unreachable!(),
    };

    // Remaining params (everything after the query).
    let remaining: Vec<_> = func.sig.inputs.iter().skip(1).cloned().collect();

    // Prepend `let <query> = Self::query();` to the function body.
    let mut stmts = func.block.stmts;
    let query_stmt: syn::Stmt = syn::parse_quote! {
        let #first_pat = Self::query();
    };
    stmts.insert(0, query_stmt);

    let expanded = quote! {
        #vis fn #public_name(#(#remaining),*) #output_ty {
            #(#stmts)*
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[route]  (on impl blocks)
//
// Scans method-level #[get("…")], #[post("…")] etc. markers and generates
// a `register_routes(&Registrar)` method.
//
// Usage:
//   #[route]
//   impl MyController {
//       #[get("/users")]
//       async fn index() -> impl IntoResponse { … }
//
//       #[post("/users")]
//       async fn store(Json(body): Json<Input>) -> impl IntoResponse { … }
//   }
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn route(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item_str = item.to_string();

    // Only process impl blocks.
    if !item_str.starts_with("impl") {
        return item;
    }

    let input: ItemImpl = syn::parse(item.clone()).unwrap();
    let self_ty = input.self_ty.clone();
    let mut registrations = Vec::new();
    let mut clean_fns = Vec::new();

    // First pass: collect registrations and rebuild clean methods.
    for method_item in &input.items {
        if let ImplItem::Fn(m) = method_item {
            let mut method_name: Option<String> = None;
            let mut uri: Option<String> = None;
            let mut middleware_names: Vec<String> = Vec::new();

            for attr in &m.attrs {
                if let Some(ident) = attr.path().get_ident() {
                    let name = ident.to_string();
                    if matches!(
                        name.as_str(),
                        "get" | "post" | "put" | "patch" | "delete" | "ws"
                    ) {
                        let parsed: UriArg = attr.parse_args().unwrap();
                        method_name = Some(name.to_uppercase());
                        uri = Some(parsed.uri);
                    } else if name == "middleware" {
                        let parsed: MiddlewareArgs = attr.parse_args().unwrap();
                        middleware_names = parsed.names;
                    }
                }
            }

            let fn_name = &m.sig.ident;
            let (attrs, vis, sig, block) = (&m.attrs, &m.vis, &m.sig, &m.block);

            // Keep attributes that are NOT route markers or middleware.
            let kept_attrs: Vec<_> = attrs
                .iter()
                .filter(|a| {
                    a.path().get_ident().map(|i| i.to_string()).is_none_or(|n| {
                        !matches!(
                            n.as_str(),
                            "get" | "post" | "put" | "patch" | "delete" | "ws" | "middleware"
                        )
                    })
                })
                .collect();

            clean_fns.push(quote! {
                #(#kept_attrs)*
                #vis #sig #block
            });

            if let (Some(method), Some(uri)) = (method_name, uri) {
                let method_ident =
                    syn::Ident::new(&method.to_lowercase(), proc_macro2::Span::call_site());

                // Set per-route middleware.
                let mw_strings: Vec<_> = middleware_names
                    .iter()
                    .map(|n| proc_macro2::Literal::string(n))
                    .collect();
                let mw_set = if mw_strings.is_empty() {
                    quote! { registrar.with_middleware(Vec::<&str>::new()); }
                } else {
                    quote! { registrar.with_middleware(vec![#(#mw_strings),*]); }
                };

                let registrar_call = if method == "WS" {
                    quote! {
                        #mw_set
                        registrar.ws(#uri, Self::#fn_name);
                    }
                } else {
                    quote! {
                        #mw_set
                        registrar.#method_ident(#uri, Self::#fn_name);
                    }
                };
                registrations.push(registrar_call);
            }
        }
    }

    let gen = quote! {
        impl #self_ty {
            #(#clean_fns)*
        }

        impl #self_ty {
            pub fn register_routes(registrar: &larastvel_core::routing::Registrar) {
                #(#registrations)*
            }
        }
    };

    TokenStream::from(gen)
}

// ---------------------------------------------------------------------------
// Attribute: #[notification]
//
// Generates a Notification trait implementation from an impl block by
// scanning for notification-specific methods (via, to_mail, to_broadcast,
// to_database, to_webhook, to_sms).  Non-notification methods remain on
// the original impl block.
//
// Usage:
// ```rust,ignore
// #[derive(Debug)]
// struct InvoicePaid {
//     invoice_id: i32,
// }
//
// #[notification]
// impl InvoicePaid {
//     fn via(&self) -> Vec<NotificationChannel> {
//         vec![NotificationChannel::Mail]
//     }
//
//     fn to_mail(&self) -> Option<Mailable> {
//         Some(Mailable::html(vec![], "Invoice Paid", "<p>...</p>"))
//     }
// }
// ```
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn notification(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);
    let struct_ty = &input.self_ty;
    let generics = &input.generics;
    let where_clause = &input.generics.where_clause;

    let known_methods: [&str; 6] = [
        "via",
        "to_mail",
        "to_broadcast",
        "to_database",
        "to_webhook",
        "to_sms",
    ];

    let mut notification_impls = Vec::new();
    let mut kept_items = Vec::new();

    for item in input.items {
        if let syn::ImplItem::Fn(method) = &item {
            if known_methods.contains(&method.sig.ident.to_string().as_str()) {
                notification_impls.push(item);
                continue;
            }
        }
        kept_items.push(item);
    }

    let expanded = quote! {
        impl #generics #struct_ty #where_clause {
            #(#kept_items)*
        }

        impl #generics larastvel_core::notifications::Notification for #struct_ty #where_clause {
            #(#notification_impls)*
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[rule]
//
// Generates a ValidationRule trait implementation from an impl block by
// scanning for a `validate` method.  The `name()` method is auto-derived
// from the struct name (snake_case).  Non-rule methods remain on the
// original impl block.
//
// Usage:
// ```rust,ignore
// #[derive(Debug, Clone)]
// struct UpperCaseRule;
//
// #[rule]
// impl UpperCaseRule {
//     fn validate(&self, field: &str, value: &str) -> Result<(), ValidationError> {
//         if value.chars().any(|c| c.is_lowercase()) {
//             return Err(ValidationError::new(
//                 format!("The {} must be uppercase.", field),
//             ));
//         }
//         Ok(())
//     }
// }
// ```
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn rule(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);
    let struct_ty = &input.self_ty;
    let generics = &input.generics;
    let where_clause = &input.generics.where_clause;

    // Derive name() from the struct name: PascalCase -> snake_case
    let struct_name = struct_ty_to_string(struct_ty);
    let rule_name = pascal_to_snake(&struct_name);

    let mut validate_method: Option<syn::ImplItemFn> = None;
    let mut kept_items = Vec::new();

    for item in input.items {
        if let syn::ImplItem::Fn(method) = &item {
            if method.sig.ident == "validate" {
                validate_method = Some(method.clone());
                continue;
            }
        }
        kept_items.push(item);
    }

    let validate = match validate_method {
        Some(m) => quote! { #m },
        None => {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                "#[rule] requires a `validate` method on the impl block",
            )
            .to_compile_error()
            .into();
        }
    };

    let expanded = quote! {
        impl #generics #struct_ty #where_clause {
            #(#kept_items)*
        }

        impl #generics larastvel_core::validation::ValidationRule for #struct_ty #where_clause {
            fn name(&self) -> &str {
                #rule_name
            }

            #validate
        }
    };

    TokenStream::from(expanded)
}

fn struct_ty_to_string(ty: &syn::Type) -> String {
    // Extract the simple type name: e.g. MyRule<T> -> "MyRule"
    match ty {
        syn::Type::Path(p) => p
            .path
            .segments
            .last()
            .map(|s| s.ident.to_string())
            .unwrap_or_default(),
        _ => String::new(),
    }
}

fn pascal_to_snake(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.char_indices() {
        if i > 0 && c.is_uppercase() {
            result.push('_');
        }
        result.push(c.to_ascii_lowercase());
    }
    result
}

// ---------------------------------------------------------------------------
// Attribute: #[observer(Model)]
//
// Generates Listener implementations for model lifecycle events based on
// hook methods defined on an impl block.
//
// The attribute goes on an impl block for an observer struct. Hook methods
// are scanned by name (`created`, `updated`, `deleted`, `saved`,
// `retrieved`) and each generates a `Listener<ModelEvent<M::Entity>>`
// implementation.  An `observe()` method is also generated to register
// all listeners with `EventService`.
//
// Usage:
// ```rust,ignore
// struct UserObserver;
//
// #[observer(User)]
// impl UserObserver {
//     async fn created(&self, model: Model) {
//         tracing::info!("User created: {}", model.email);
//     }
//
//     async fn deleted(&self, model: Model) {
//         tracing::info!("User deleted: {}", model.email);
//     }
// }
//
// // Register the observer at app boot:
// UserObserver::observe();
// ```
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn observer(attr: TokenStream, item: TokenStream) -> TokenStream {
    let model_ty: syn::Type = parse_macro_input!(attr as syn::Type);
    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);

    let struct_ty = &input.self_ty;

    let entity_ty = quote! {
        <#model_ty as larastvel_core::models::DbModel>::Entity
    };
    let event_mod = quote! { larastvel_core::events };
    let listener_trait = quote! { larastvel_core::events::Listener };

    // Known hook method names and their corresponding event type stems
    let hooks: [(&str, &str); 5] = [
        ("created", "ModelCreated"),
        ("updated", "ModelUpdated"),
        ("deleted", "ModelDeleted"),
        ("saved", "ModelSaved"),
        ("retrieved", "ModelRetrieved"),
    ];

    // Scan the impl block for hook methods
    let mut listener_impls = Vec::new();
    let mut observe_calls = Vec::new();

    for item in &input.items {
        if let syn::ImplItem::Fn(method) = item {
            let method_name = method.sig.ident.to_string();
            if let Some(&(_, event_stem)) = hooks.iter().find(|(name, _)| *name == method_name) {
                let event_ident = syn::Ident::new(event_stem, method.sig.ident.span());
                let hook_method = &method.sig.ident;

                // Generate Listener<ModelEvent<M::Entity>> implementation
                listener_impls.push(quote! {
                    #[larastvel_core::async_trait]
                    impl #listener_trait<#event_mod::#event_ident<#entity_ty>> for #struct_ty {
                        async fn handle(&self, event: #event_mod::#event_ident<#entity_ty>) {
                            self.#hook_method(event.0).await;
                        }
                    }
                });

                // Generate the observe() registration call
                observe_calls.push(quote! {
                    larastvel_core::events::EventService::listen::<#event_mod::#event_ident<#entity_ty>, Self>(Self);
                });
            }
        }
    }

    let expanded = quote! {
        #input

        #(#listener_impls)*

        impl #struct_ty {
            /// Register this observer's hook methods as event listeners.
            pub fn observe() {
                #(#observe_calls)*
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: command
// ---------------------------------------------------------------------------

struct CommandArgs {
    name: String,
    description: String,
}

impl Parse for CommandArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: syn::LitStr = input.parse()?;
        let mut description = String::new();
        if input.peek(syn::Token![,]) {
            input.parse::<syn::Token![,]>()?;
            let ident: syn::Ident = input.parse()?;
            if ident == "description" {
                input.parse::<syn::Token![=]>()?;
                description = input.parse::<syn::LitStr>()?.value();
            }
        }
        Ok(CommandArgs {
            name: name.value(),
            description,
        })
    }
}

#[proc_macro_attribute]
pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as CommandArgs);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;

    let command_name = &args.name;
    let description = &args.description;

    let expanded = quote! {
        #input

        impl larastvel_core::console::Command for #name {
            fn name(&self) -> &'static str {
                #command_name
            }

            fn description(&self) -> &'static str {
                #description
            }

            fn handle(
                &self,
                app: &larastvel_core::foundation::Application,
                args: &[String],
            ) -> Result<(), larastvel_core::console::ConsoleError> {
                self.run(app, args)
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: policy
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn policy(attr: TokenStream, item: TokenStream) -> TokenStream {
    let resource_name = parse_macro_input!(attr as syn::LitStr);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let resource = resource_name.value();

    let expanded = quote! {
        #input

        impl #name {
            /// Register this policy with the given gate.
            pub fn register(gate: &larastvel_core::auth::Gate) {
                gate.register_policy(#resource, std::sync::Arc::new(#name));
            }
        }

        impl larastvel_core::auth::Policy for #name {
            fn resource(&self) -> &str {
                #resource
            }

            fn check(
                &self,
                user: &larastvel_core::auth::AuthenticatedUser,
                ability: &str,
                args: &[String],
            ) -> Option<larastvel_core::auth::GateCheck> {
                self.check_ability(user, ability, args)
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: factory
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn factory(attr: TokenStream, item: TokenStream) -> TokenStream {
    let model_name = parse_macro_input!(attr as syn::LitStr);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let model = model_name.value();
    let model_ident = syn::Ident::new(&model, model_name.span());

    let expanded = quote! {
        #input

        impl larastvel_core::models::factory::ModelFactory for #name {
            type ActiveModel = crate::models::#model_ident::ActiveModel;

            fn definition() -> Self::ActiveModel {
                Self::define()
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: seeder
// ---------------------------------------------------------------------------

struct SeederArgs {
    name: Option<String>,
}

impl Parse for SeederArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.is_empty() {
            Ok(SeederArgs { name: None })
        } else {
            let name: syn::LitStr = input.parse()?;
            Ok(SeederArgs {
                name: Some(name.value()),
            })
        }
    }
}

#[proc_macro_attribute]
pub fn seeder(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as SeederArgs);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let seeder_name = args
        .name
        .unwrap_or_else(|| pascal_to_snake(&name.to_string()));

    let expanded = quote! {
        #input

        #[larastvel_core::async_trait]
        impl larastvel_core::database::Seeder for #name {
            fn name() -> &'static str {
                #seeder_name
            }

            async fn run(
                conn: &larastvel_core::sea_orm::DbConn,
            ) -> Result<(), Box<dyn std::error::Error>> {
                Self::seed(conn).await
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: provider
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn provider(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;

    let expanded = quote! {
        #input

        impl larastvel_core::foundation::ServiceProvider for #name {
            fn register(&self, app: &larastvel_core::foundation::Application) {
                self.register_services(app)
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: api_resource
// ---------------------------------------------------------------------------

struct ApiResourceArgs {
    model_type: syn::Type,
}

impl Parse for ApiResourceArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let model_type: syn::Type = input.parse()?;
        Ok(ApiResourceArgs { model_type })
    }
}

#[proc_macro_attribute]
pub fn api_resource(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as ApiResourceArgs);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let model_ty = &args.model_type;

    let expanded = quote! {
        #input

        impl larastvel_core::models::serialization::ApiResource<#model_ty> for #name {
            fn transform(model: &#model_ty) -> serde_json::Value {
                Self::to_array(model)
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: json_api_resource
// ---------------------------------------------------------------------------

struct JsonApiResourceArgs {
    model_type: syn::Type,
}

impl Parse for JsonApiResourceArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let model_type: syn::Type = input.parse()?;
        Ok(JsonApiResourceArgs { model_type })
    }
}

#[proc_macro_attribute]
pub fn json_api_resource(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as JsonApiResourceArgs);
    let input = parse_macro_input!(item as ItemImpl);
    let name = &input.self_ty;
    let model_ty = &args.model_type;

    let mut methods = std::collections::HashSet::new();
    for impl_item in &input.items {
        if let syn::ImplItem::Fn(fun) = impl_item {
            methods.insert(fun.sig.ident.to_string());
        }
    }

    let mut generated = Vec::new();
    if methods.contains("attributes") {
        generated.push(quote! {
            fn attributes(model: &#model_ty) -> serde_json::Value {
                Self::attributes(model)
            }
        });
    }
    if methods.contains("id") {
        generated.push(quote! {
            fn id(model: &#model_ty) -> String {
                Self::id(model)
            }
        });
    }
    if methods.contains("type_") {
        generated.push(quote! {
            fn type_() -> String {
                Self::type_()
            }
        });
    }
    if methods.contains("relationships") {
        generated.push(quote! {
            fn relationships(
                model: &#model_ty,
                query: &larastvel_core::models::jsonapi::JsonApiQuery,
            ) -> serde_json::Value {
                Self::relationships(model, query)
            }
        });
    }
    if methods.contains("links") {
        generated.push(quote! {
            fn links(model: &#model_ty) -> serde_json::Value {
                Self::links(model)
            }
        });
    }
    if methods.contains("meta") {
        generated.push(quote! {
            fn meta(model: &#model_ty) -> serde_json::Value {
                Self::meta(model)
            }
        });
    }

    let expanded = quote! {
        #input

        impl larastvel_core::models::jsonapi::JsonApiResource<#model_ty> for #name {
            #(#generated)*
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: broadcast_event
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn broadcast_event(attr: TokenStream, item: TokenStream) -> TokenStream {
    let event_name = parse_macro_input!(attr as syn::LitStr);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let name_str = event_name.value();

    let expanded = quote! {
        #input

        impl larastvel_core::broadcasting::BroadcastEvent for #name {
            fn broadcast_event_name(&self) -> &str {
                #name_str
            }

            fn broadcast_channels(&self) -> Vec<larastvel_core::broadcasting::Channel> {
                self.channels()
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: mail
// ---------------------------------------------------------------------------

struct MailArgs {
    subject: String,
    from: Option<String>,
    reply_to: Option<String>,
}

impl Parse for MailArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut subject = None;
        let mut from = None;
        let mut reply_to = None;

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            input.parse::<syn::Token![=]>()?;
            let value: syn::LitStr = input.parse()?;
            match ident.to_string().as_str() {
                "subject" => subject = Some(value.value()),
                "from" => from = Some(value.value()),
                "reply_to" => reply_to = Some(value.value()),
                other => {
                    return Err(syn::Error::new(
                        ident.span(),
                        format!("unknown mail argument: {}", other),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<syn::Token![,]>()?;
            }
        }

        let subject = subject.ok_or_else(|| {
            syn::Error::new(proc_macro2::Span::call_site(), "#[mail] requires `subject`")
        })?;

        Ok(MailArgs {
            subject,
            from,
            reply_to,
        })
    }
}

#[proc_macro_attribute]
pub fn mail(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as MailArgs);
    let input = parse_macro_input!(item as ItemStruct);
    let name = &input.ident;
    let subject = &args.subject;

    let from_chain = args.from.as_ref().map(|f| {
        quote! { .from(#f) }
    });

    let reply_to_chain = args.reply_to.as_ref().map(|r| {
        quote! { .reply_to(#r) }
    });

    let expanded = quote! {
        #input

        impl #name {
            /// Send this mail using the given mailer.
            pub async fn send(
                &self,
                mailer: &dyn larastvel_core::mail::Mailer,
            ) -> Result<(), larastvel_core::mail::MailError> {
                let mailable = larastvel_core::mail::Mailable::html(
                    self.to.clone(),
                    #subject,
                    &self.html(),
                )
                #from_chain
                #reply_to_chain;
                mailer.send(mailable).await
            }
        }
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Attribute: #[bind_when(alias = "name", condition_key = "config.path")]
//
// Mirrors Laravel 13.22's `#[BindWhen]`: declares a conditional container
// binding on a trait. Conditions are evaluated at resolve time; when the
// config value at `condition_key` is truthy, the binding resolves the
// configured instance for the trait's alias.
//
// Usage:
//   #[bind_when(alias = "payment-gateway", condition_key = "features.payments.beta")]
//   trait PaymentGateway: Send + Sync + 'static {}
//
// Expands to (in addition to the original trait) a companion struct
// `PaymentGatewayConditionalBindings` with:
//   pub const ALIAS: &'static str = "payment-gateway";
//   pub const CONDITION_KEY: &'static str = "features.payments.beta";
//   pub fn conditional_enabled(app: &Application) -> bool;
//   pub fn register_conditional_binding(
//       app, when_enabled: impl FnOnce() -> Arc<dyn PaymentGateway>,
//   ) { app.bind_if_config(...); }
//   pub fn resolve(app) -> Option<Arc<dyn PaymentGateway>> { ... }
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn bind_when(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as BindWhenArgs);
    let input = parse_macro_input!(item as ItemTrait);
    let name = &input.ident;
    let helper = syn::Ident::new(&format!("{}ConditionalBindings", name), name.span());
    let alias = &args.alias;
    let condition_key = &args.condition_key;

    let expanded = quote! {
        #input

        /// Auto-generated registry for this trait's `#[bind_when]` conditional
        /// container bindings (declared next to the trait, like Laravel's
        /// `#[BindWhen]` attribute).
        #[allow(non_camel_case_types)]
        pub struct #helper;

        impl #helper {
            /// The container alias registered for this trait's conditional bindings.
            pub const ALIAS: &'static str = #alias;

            /// Config key gating the conditional binding.
            pub const CONDITION_KEY: &'static str = #condition_key;

            /// Whether the conditional binding is currently enabled per config.
            pub fn conditional_enabled(app: &larastvel_core::foundation::Application) -> bool {
                app.config_bool(Self::CONDITION_KEY)
            }

            /// Register this trait's conditional binding.
            ///
            /// The binding is stored under [`Self::ALIAS`] and can be resolved
            /// again with [`resolve`](Self::resolve). Conditions are evaluated
            /// at resolve time against the live application config.
            pub fn register_conditional_binding(
                app: &larastvel_core::foundation::Application,
                when_enabled: impl FnOnce() -> std::sync::Arc<dyn #name>,
            ) {
                app.bind_if_config(Self::ALIAS, Self::CONDITION_KEY, when_enabled());
            }

            /// Resolve the conditional binding for this trait, if the
            /// condition is currently satisfied.
            pub fn resolve(
                app: &larastvel_core::foundation::Application,
            ) -> Option<std::sync::Arc<dyn #name>> {
                app.make_by_alias(Self::ALIAS)
            }
        }
    };

    TokenStream::from(expanded)
}

struct BindWhenArgs {
    alias: String,
    condition_key: String,
}

impl Parse for BindWhenArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut alias = None;
        let mut condition_key = None;

        while !input.is_empty() {
            let ident: Ident = input.parse()?;
            input.parse::<syn::Token![=]>()?;
            let value: LitStr = input.parse()?;
            let name = ident.to_string();
            if name == "alias" {
                alias = Some(value.value());
            } else if name == "condition_key" {
                condition_key = Some(value.value());
            } else {
                return Err(syn::Error::new(
                    ident.span(),
                    format!("unknown #[bind_when] attribute: {name}"),
                ));
            }
            if !input.is_empty() {
                input.parse::<syn::Token![,]>()?;
            }
        }

        Ok(BindWhenArgs {
            alias: alias.ok_or_else(|| input.error("missing `alias = \"...\"` argument"))?,
            condition_key: condition_key
                .ok_or_else(|| input.error("missing `condition_key = \"...\"` argument"))?,
        })
    }
}