vespera_macro 0.1.42

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
//! File system operations for finding struct definitions
//!
//! Provides functions to locate struct definitions in source files.

use std::path::Path;

use syn::Type;

use crate::metadata::StructMetadata;
use std::path::PathBuf;

/// Build candidate file paths from module segments.
///
/// Given a source directory and module segments (e.g., `["models", "memo"]`),
/// returns both `{src_dir}/models/memo.rs` and `{src_dir}/models/memo/mod.rs`.
#[inline]
fn candidate_file_paths(src_dir: &Path, module_segments: &[&str]) -> [PathBuf; 2] {
    let joined = module_segments.join("/");
    [
        src_dir.join(format!("{joined}.rs")),
        src_dir.join(format!("{joined}/mod.rs")),
    ]
}

/// Try to find a struct definition from a module path by reading source files.
///
/// This allows `schema_type`! to work with structs defined in other files, like:
/// ```ignore
/// // In src/routes/memos.rs
/// schema_type!(CreateMemoRequest from models::memo::Model, pick = ["title", "content"]);
/// ```
///
/// The function will:
/// 1. Parse the path (e.g., `models::memo::Model` or `crate::models::memo::Model`)
/// 2. Convert to file path (e.g., `src/models/memo.rs`)
/// 3. Read and parse the file to find the struct definition
///
/// For simple names (e.g., just `Model` without module path), it will scan all `.rs`
/// files in `src/` to find the struct. This supports same-file usage like:
/// ```ignore
/// pub struct Model { ... }
/// vespera::schema_type!(Schema from Model, name = "UserSchema");
/// ```
///
/// The `schema_name_hint` is used to disambiguate when multiple structs with the same
/// name exist. For example, with `name = "UserSchema"`, it will prefer `user.rs`.
///
/// Returns `(StructMetadata, Vec<String>)` where the Vec is the module path.
/// For qualified paths, this is extracted from the type itself.
/// For simple names, it's inferred from the file location.
pub fn find_struct_from_path(
    ty: &Type,
    schema_name_hint: Option<&str>,
) -> Option<(StructMetadata, Vec<String>)> {
    // Get CARGO_MANIFEST_DIR to locate src folder (cached to avoid repeated syscalls)
    let manifest_dir = super::file_cache::get_manifest_dir()?;
    let src_dir = Path::new(&manifest_dir).join("src");

    // Extract path segments from the type
    let Type::Path(type_path) = ty else {
        return None;
    };

    let segments: Vec<String> = type_path
        .path
        .segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect();

    if segments.is_empty() {
        return None;
    }

    // The last segment is the struct name
    let struct_name = segments.last()?.clone();

    // Build possible file paths from the module path
    // e.g., models::memo::Model -> src/models/memo.rs or src/models/memo/mod.rs
    // e.g., crate::models::memo::Model -> src/models/memo.rs
    let module_segments: Vec<&str> = segments[..segments.len() - 1]
        .iter()
        .filter(|s| *s != "crate" && *s != "self" && *s != "super")
        .map(std::string::String::as_str)
        .collect();

    // If no module path (simple name like `Model`), scan all files with schema_name hint
    if module_segments.is_empty() {
        return find_struct_by_name_in_all_files(&src_dir, &struct_name, schema_name_hint);
    }

    // For qualified paths, the module path is extracted from the type itself
    // e.g., crate::models::memo::Model -> ["crate", "models", "memo"]
    let type_module_path: Vec<String> = segments[..segments.len() - 1].to_vec();

    // Try different file path patterns
    let file_paths = candidate_file_paths(&src_dir, &module_segments);

    for file_path in file_paths {
        if !file_path.exists() {
            continue;
        }
        if let Some(definition) = super::file_cache::get_struct_definition(&file_path, &struct_name)
        {
            return Some((
                StructMetadata::new_model(struct_name, definition),
                type_module_path,
            ));
        }
    }

    None
}

/// Find a struct by name by scanning all `.rs` files in the src directory.
///
/// This is used as a fallback when the type path doesn't include module information
/// (e.g., just `Model` instead of `crate::models::user::Model`).
///
/// Resolution strategy:
/// 1. If exactly one struct with the name exists -> use it
/// 2. If multiple exist and `schema_name_hint` is provided (e.g., "UserSchema"):
///    -> Prefer file whose name contains the hint prefix (e.g., "user.rs" for "`UserSchema`")
/// 3. Otherwise -> return None (ambiguous)
///
/// The `schema_name_hint` is the custom schema name (e.g., "`UserSchema`", "`MemoSchema`")
/// which often contains a hint about the module name.
///
/// Returns `(StructMetadata, Vec<String>)` where the Vec is the inferred module path
/// from the file location (e.g., `["crate", "models", "user"]`).
#[allow(clippy::too_many_lines)]
pub fn find_struct_by_name_in_all_files(
    src_dir: &Path,
    struct_name: &str,
    schema_name_hint: Option<&str>,
) -> Option<(StructMetadata, Vec<String>)> {
    // Use cached struct-candidate index: files already filtered by text search
    let mut rs_files = super::file_cache::get_struct_candidates(src_dir, struct_name);

    // Pre-compute hint prefix once (used in fast path and fallback disambiguation)
    let prefix_normalized = schema_name_hint.map(derive_hint_prefix);

    // FAST PATH: If schema_name_hint is provided, try matching files first.
    // This avoids parsing ALL files for the common same-file pattern:
    //   schema_type!(Schema from Model, name = "UserSchema")  in user.rs
    if let Some(prefix_normalized) = &prefix_normalized {
        // Partition files: candidate files (filename matches hint prefix) vs rest
        let (candidates, rest): (Vec<_>, Vec<_>) = rs_files.into_iter().partition(|path| {
            path.file_stem()
                .and_then(|s| s.to_str())
                .is_some_and(|name| {
                    let norm = normalize_name(name);
                    norm == *prefix_normalized || norm.contains(prefix_normalized.as_str())
                })
        });

        // Parse only candidate files first
        let mut found_in_candidates: Vec<(std::path::PathBuf, StructMetadata)> = Vec::new();
        for file_path in &candidates {
            if let Some(definition) =
                super::file_cache::get_struct_definition(file_path, struct_name)
            {
                found_in_candidates.push((
                    file_path.clone(),
                    StructMetadata::new_model(struct_name.to_string(), definition),
                ));
            }
        }

        // If exactly one match in candidates, return immediately (fast path hit!)
        if found_in_candidates.len() == 1 {
            let (path, metadata) = found_in_candidates.remove(0);
            let module_path = file_path_to_module_path(&path, src_dir);
            return Some((metadata, module_path));
        }

        // If candidates found multiple, try disambiguation by exact filename match
        if found_in_candidates.len() > 1 {
            let exact_match: Vec<_> = found_in_candidates
                .iter()
                .filter(|(path, _)| {
                    path.file_stem()
                        .and_then(|s| s.to_str())
                        .is_some_and(|name| normalize_name(name) == *prefix_normalized)
                })
                .collect();

            if exact_match.len() == 1 {
                let (path, metadata) = exact_match[0];
                let module_path = file_path_to_module_path(path, src_dir);
                return Some((metadata.clone(), module_path));
            }

            // Still ambiguous among candidates
            return None;
        }

        // No match in candidates — fall through to scan remaining files
        rs_files = rest;
    }

    // FULL SCAN: Parse all remaining files (or all files if no hint)
    let mut found_structs: Vec<(std::path::PathBuf, StructMetadata)> = Vec::new();

    for file_path in rs_files {
        if let Some(definition) = super::file_cache::get_struct_definition(&file_path, struct_name)
        {
            found_structs.push((
                file_path.clone(),
                StructMetadata::new_model(struct_name.to_string(), definition),
            ));
        }
    }

    match found_structs.len() {
        1 => {
            let (path, metadata) = found_structs.remove(0);
            let module_path = file_path_to_module_path(&path, src_dir);
            Some((metadata, module_path))
        }
        _ => None,
    }
}

/// Derive a normalized prefix from a schema name hint for file matching.
///
/// Strips common suffixes ("Schema", "Response", "Request") and normalizes
/// by removing underscores and lowercasing.
///
/// # Examples
/// - "UserSchema" → "user"
/// - "MemoResponse" → "memo"
/// - "AdminUserSchema" → "adminuser"
fn derive_hint_prefix(hint: &str) -> String {
    let hint_lower = hint.to_lowercase();
    let prefix = hint_lower
        .strip_suffix("schema")
        .or_else(|| hint_lower.strip_suffix("response"))
        .or_else(|| hint_lower.strip_suffix("request"))
        .unwrap_or(&hint_lower);
    normalize_name(prefix)
}

/// Normalize a name by lowercasing and removing underscores in a single pass.
/// Replaces the two-allocation `s.to_lowercase().replace('_', "")` pattern.
#[inline]
fn normalize_name(s: &str) -> String {
    s.chars()
        .filter(|&c| c != '_')
        .map(|c| c.to_ascii_lowercase())
        .collect()
}

/// Recursively collect all `.rs` files in a directory.
pub fn collect_rs_files_recursive(dir: &Path, files: &mut Vec<std::path::PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_rs_files_recursive(&path, files);
        } else if path.extension().is_some_and(|ext| ext == "rs") {
            files.push(path);
        }
    }
}

/// Derive module path from a file path relative to src directory.
///
/// Examples:
/// - `src/models/user.rs` -> `["crate", "models", "user"]`
/// - `src/models/user/mod.rs` -> `["crate", "models", "user"]`
/// - `src/lib.rs` -> `["crate"]`
pub fn file_path_to_module_path(file_path: &Path, src_dir: &Path) -> Vec<String> {
    let Ok(relative) = file_path.strip_prefix(src_dir) else {
        return vec!["crate".to_string()];
    };

    let mut segments = vec!["crate".to_string()];

    for component in relative.components() {
        if let std::path::Component::Normal(os_str) = component
            && let Some(s) = os_str.to_str()
        {
            // Handle .rs extension
            if let Some(name) = s.strip_suffix(".rs") {
                // Skip mod.rs and lib.rs - they don't add a segment
                if name != "mod" && name != "lib" {
                    segments.push(name.to_string());
                }
            } else {
                // Directory name
                segments.push(s.to_string());
            }
        }
    }

    segments
}

/// Find struct definition from a schema path string (e.g., "`crate::models::user::Schema`").
///
/// Similar to `find_struct_from_path` but takes a string path instead of `syn::Type`.
pub fn find_struct_from_schema_path(path_str: &str) -> Option<StructMetadata> {
    // Get CARGO_MANIFEST_DIR to locate src folder (cached to avoid repeated syscalls)
    let manifest_dir = super::file_cache::get_manifest_dir()?;
    let src_dir = Path::new(&manifest_dir).join("src");

    // Parse the path string into segments
    let segments: Vec<&str> = path_str.split("::").filter(|s| !s.is_empty()).collect();

    if segments.is_empty() {
        return None;
    }

    // The last segment is the struct name
    let struct_name = segments.last()?.to_string();

    // Build possible file paths from the module path
    // e.g., crate::models::user::Schema -> src/models/user.rs
    let module_segments: Vec<&str> = segments[..segments.len() - 1]
        .iter()
        .filter(|s| **s != "crate" && **s != "self" && **s != "super")
        .copied()
        .collect();

    if module_segments.is_empty() {
        return None;
    }

    // Try different file path patterns
    let file_paths = candidate_file_paths(&src_dir, &module_segments);

    for file_path in file_paths {
        if !file_path.exists() {
            continue;
        }
        if let Some(definition) = super::file_cache::get_struct_definition(&file_path, &struct_name)
        {
            return Some(StructMetadata::new_model(struct_name, definition));
        }
    }

    None
}

/// Find the FK column name from the target entity for a `HasMany` relation with `via_rel`.
///
/// When a `HasMany` relation has `via_rel = "TargetUser"`, this function:
/// 1. Looks up the target entity file (e.g., notification.rs from schema path)
/// 2. Finds the field with matching `relation_enum = "TargetUser"`
/// 3. Extracts and returns the `from` attribute value (e.g., "`target_user_id`")
///
/// Returns None if the target file can't be found or parsed, or if no matching relation exists.
#[allow(clippy::too_many_lines)]
pub fn find_fk_column_from_target_entity(
    target_schema_path: &str,
    via_rel: &str,
) -> Option<String> {
    use crate::schema_macro::seaorm::{extract_belongs_to_from_field, extract_relation_enum};

    // Get CARGO_MANIFEST_DIR to locate src folder (cached to avoid repeated syscalls)
    let manifest_dir = super::file_cache::get_manifest_dir()?;
    let src_dir = Path::new(&manifest_dir).join("src");

    // Parse the schema path to get file path
    // e.g., "crate :: models :: notification :: Schema" -> src/models/notification.rs
    let segments: Vec<&str> = target_schema_path
        .split("::")
        .map(str::trim)
        .filter(|s| !s.is_empty() && *s != "Schema" && *s != "Entity")
        .collect();

    let module_segments: Vec<&str> = segments
        .iter()
        .filter(|s| **s != "crate" && **s != "self" && **s != "super")
        .copied()
        .collect();

    if module_segments.is_empty() {
        return None;
    }

    // Try different file path patterns
    let file_paths = candidate_file_paths(&src_dir, &module_segments);

    for file_path in file_paths {
        if !file_path.exists() {
            continue;
        }

        let Some(model_def) = super::file_cache::get_struct_definition(&file_path, "Model") else {
            continue;
        };
        let Ok(model) = super::file_cache::parse_struct_cached(&model_def) else {
            continue;
        };

        // Search through fields for the one with matching relation_enum
        if let syn::Fields::Named(fields_named) = &model.fields {
            for field in &fields_named.named {
                let field_relation_enum = extract_relation_enum(&field.attrs);
                if field_relation_enum.as_deref() == Some(via_rel) {
                    // Found the matching field, extract FK column from `from` attribute
                    return extract_belongs_to_from_field(&field.attrs);
                }
            }
        }
    }

    None
}

/// Find the Model definition from a Schema path.
/// Converts "`crate::models::user::Schema`" -> finds Model in src/models/user.rs
#[allow(clippy::too_many_lines)]
pub fn find_model_from_schema_path(schema_path_str: &str) -> Option<StructMetadata> {
    // Get CARGO_MANIFEST_DIR to locate src folder (cached to avoid repeated syscalls)
    let manifest_dir = super::file_cache::get_manifest_dir()?;
    let src_dir = Path::new(&manifest_dir).join("src");

    // Parse the path string and convert Schema path to module path
    // e.g., "crate :: models :: user :: Schema" -> ["crate", "models", "user"]
    let segments: Vec<&str> = schema_path_str
        .split("::")
        .map(str::trim)
        .filter(|s| !s.is_empty() && *s != "Schema")
        .collect();

    if segments.is_empty() {
        return None;
    }

    // Build possible file paths from the module path
    let module_segments: Vec<&str> = segments
        .iter()
        .filter(|s| **s != "crate" && **s != "self" && **s != "super")
        .copied()
        .collect();

    if module_segments.is_empty() {
        return None;
    }

    // Try different file path patterns
    let file_paths = candidate_file_paths(&src_dir, &module_segments);

    for file_path in file_paths {
        if !file_path.exists() {
            continue;
        }
        if let Some(definition) = super::file_cache::get_struct_definition(&file_path, "Model") {
            return Some(StructMetadata::new_model("Model".to_string(), definition));
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use serial_test::serial;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_file_path_to_module_path_simple() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();
        let file_path = src_dir.join("models").join("user.rs");
        let result = file_path_to_module_path(&file_path, src_dir);
        assert_eq!(result, vec!["crate", "models", "user"]);
    }

    #[test]
    fn test_file_path_to_module_path_mod_rs() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();
        let file_path = src_dir.join("models").join("mod.rs");
        let result = file_path_to_module_path(&file_path, src_dir);
        assert_eq!(result, vec!["crate", "models"]);
    }

    #[test]
    fn test_file_path_to_module_path_lib_rs() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();
        let file_path = src_dir.join("lib.rs");
        let result = file_path_to_module_path(&file_path, src_dir);
        assert_eq!(result, vec!["crate"]);
    }

    #[test]
    fn test_file_path_to_module_path_not_under_src() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let file_path = temp_dir.path().join("other").join("file.rs");
        let result = file_path_to_module_path(&file_path, &src_dir);
        assert_eq!(result, vec!["crate"]);
    }

    #[test]
    fn test_collect_rs_files_recursive_empty_dir() {
        let temp_dir = TempDir::new().unwrap();
        let mut files = Vec::new();
        collect_rs_files_recursive(temp_dir.path(), &mut files);
        assert!(files.is_empty());
    }

    #[test]
    fn test_collect_rs_files_recursive_nonexistent_dir() {
        let mut files = Vec::new();
        collect_rs_files_recursive(Path::new("/nonexistent/path"), &mut files);
        assert!(files.is_empty());
    }

    #[test]
    fn test_collect_rs_files_recursive_with_files() {
        let temp_dir = TempDir::new().unwrap();

        // Create some .rs files
        std::fs::write(temp_dir.path().join("main.rs"), "fn main() {}").unwrap();
        std::fs::create_dir(temp_dir.path().join("models")).unwrap();
        std::fs::write(
            temp_dir.path().join("models").join("user.rs"),
            "struct User;",
        )
        .unwrap();
        std::fs::write(temp_dir.path().join("other.txt"), "not a rust file").unwrap();

        let mut files = Vec::new();
        collect_rs_files_recursive(temp_dir.path(), &mut files);

        assert_eq!(files.len(), 2);
        assert!(files.iter().all(|f| f.extension().unwrap() == "rs"));
    }

    // ============================================================
    // Coverage tests for find_struct_from_path
    // ============================================================

    #[test]
    fn test_find_struct_from_path_non_path_type() {
        // Tests: Type is not a Path type -> returns None
        use syn::Type;

        // Create a reference type (not a path type)
        let ty: Type = syn::parse_str("&str").unwrap();

        // Save original CARGO_MANIFEST_DIR
        let original = std::env::var("CARGO_MANIFEST_DIR").ok();

        // Set a temporary manifest dir (doesn't matter since we'll return early)
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result = find_struct_from_path(&ty, None);

        // Restore
        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Non-path type should return None");
    }

    #[test]
    fn test_find_struct_from_path_empty_segments() {
        // Tests: Type path with empty segments -> returns None
        use syn::{Path, TypePath};

        // Construct a TypePath with empty segments
        let empty_path = Path {
            leading_colon: None,
            segments: syn::punctuated::Punctuated::new(),
        };
        let ty = Type::Path(TypePath {
            qself: None,
            path: empty_path,
        });

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result = find_struct_from_path(&ty, None);

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Empty segments should return None");
    }

    #[test]
    #[serial]
    fn test_find_struct_from_path_file_with_non_matching_items() {
        // Tests: File contains items that are not the target struct
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create a file with multiple items, only one matching
        let content = r"
pub enum SomeEnum { A, B }
pub fn some_function() {}
pub const SOME_CONST: i32 = 42;
pub trait SomeTrait {}
pub struct NotTarget { pub x: i32 }
pub struct Target { pub id: i32 }
";
        std::fs::write(models_dir.join("mixed.rs"), content).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let ty: Type = syn::parse_str("crate::models::mixed::Target").unwrap();
        let result = find_struct_from_path(&ty, None);

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_some(), "Should find Target struct");
        let (metadata, _) = result.unwrap();
        assert!(metadata.definition.contains("Target"));
    }

    // ============================================================
    // Coverage tests for find_struct_by_name_in_all_files
    // ============================================================

    #[test]
    #[serial]
    fn test_find_struct_by_name_unreadable_file() {
        // Tests for error continuation
        // Create broken symlink that exists but can't be read
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // Valid file
        std::fs::write(
            src_dir.join("valid.rs"),
            "pub struct Target { pub id: i32 }",
        )
        .unwrap();

        // Broken symlink -> read_to_string fails -> line 122
        let broken = src_dir.join("broken.rs");
        let nonexistent = src_dir.join("nonexistent");
        #[cfg(unix)]
        let _ = std::os::unix::fs::symlink(&nonexistent, &broken);
        #[cfg(windows)]
        let _ = std::os::windows::fs::symlink_file(&nonexistent, &broken);

        let result = find_struct_by_name_in_all_files(src_dir, "Target", None);

        assert!(
            result.is_some(),
            "Should find Target, skipping broken symlink"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_by_name_unparseable_file() {
        // Tests: File cannot be parsed -> continue to next file
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // Create an unparseable file
        std::fs::write(src_dir.join("broken.rs"), "this is not valid rust {{{{").unwrap();

        // Create a valid file with the struct
        std::fs::write(
            src_dir.join("valid.rs"),
            "pub struct Target { pub id: i32 }",
        )
        .unwrap();

        let result = find_struct_by_name_in_all_files(src_dir, "Target", None);

        assert!(
            result.is_some(),
            "Should find Target in valid file, skipping broken"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_with_hint() {
        // Tests: Multiple structs with same name, schema_name_hint disambiguates
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // Create user.rs with Model
        std::fs::create_dir(src_dir.join("models")).unwrap();
        std::fs::write(
            src_dir.join("models").join("user.rs"),
            "pub struct Model { pub id: i32, pub name: String }",
        )
        .unwrap();

        // Create memo.rs with Model (same struct name)
        std::fs::write(
            src_dir.join("models").join("memo.rs"),
            "pub struct Model { pub id: i32, pub title: String }",
        )
        .unwrap();

        // Without hint - should return None (ambiguous)
        let result_no_hint = find_struct_by_name_in_all_files(src_dir, "Model", None);
        assert!(
            result_no_hint.is_none(),
            "Without hint, multiple Models should be ambiguous"
        );

        // With hint "UserSchema" - should find user.rs
        let result_with_hint =
            find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));
        assert!(
            result_with_hint.is_some(),
            "With UserSchema hint, should find user.rs"
        );
        let (metadata, module_path) = result_with_hint.unwrap();
        assert!(
            metadata.definition.contains("name"),
            "Should be user Model with name field"
        );
        assert!(
            module_path.contains(&"user".to_string()),
            "Module path should contain 'user'"
        );

        // With hint "MemoSchema" - should find memo.rs
        let result_memo = find_struct_by_name_in_all_files(src_dir, "Model", Some("MemoSchema"));
        assert!(
            result_memo.is_some(),
            "With MemoSchema hint, should find memo.rs"
        );
        let (metadata_memo, _) = result_memo.unwrap();
        assert!(
            metadata_memo.definition.contains("title"),
            "Should be memo Model with title field"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_with_response_suffix() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        std::fs::create_dir(src_dir.join("models")).unwrap();
        std::fs::write(
            src_dir.join("models").join("user.rs"),
            "pub struct Data { pub id: i32 }",
        )
        .unwrap();
        std::fs::write(
            src_dir.join("models").join("item.rs"),
            "pub struct Data { pub name: String }",
        )
        .unwrap();

        // With hint "UserResponse" - should find user.rs
        let result = find_struct_by_name_in_all_files(src_dir, "Data", Some("UserResponse"));
        assert!(
            result.is_some(),
            "With UserResponse hint, should find user.rs"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_with_request_suffix() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        std::fs::create_dir(src_dir.join("models")).unwrap();
        std::fs::write(
            src_dir.join("models").join("user.rs"),
            "pub struct Input { pub id: i32 }",
        )
        .unwrap();
        std::fs::write(
            src_dir.join("models").join("item.rs"),
            "pub struct Input { pub name: String }",
        )
        .unwrap();

        // With hint "UserRequest" - should find user.rs
        let result = find_struct_by_name_in_all_files(src_dir, "Input", Some("UserRequest"));
        assert!(
            result.is_some(),
            "With UserRequest hint, should find user.rs"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_still_ambiguous() {
        // Tests: Multiple matches even after applying hint -> returns None
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // Create two files that both match the hint
        std::fs::create_dir(src_dir.join("models")).unwrap();
        std::fs::write(
            src_dir.join("models").join("user_admin.rs"),
            "pub struct Model { pub id: i32 }",
        )
        .unwrap();
        std::fs::write(
            src_dir.join("models").join("user_regular.rs"),
            "pub struct Model { pub name: String }",
        )
        .unwrap();

        // With hint "UserSchema" - both user_admin.rs and user_regular.rs match
        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));
        assert!(
            result.is_none(),
            "Multiple files matching hint should still be ambiguous"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_snake_case_filename() {
        // Tests: CamelCase schema name matches snake_case filename
        // e.g., "AdminUserSchema" should match "admin_user.rs"
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        std::fs::create_dir(src_dir.join("models")).unwrap();
        // Create admin_user.rs with Model
        std::fs::write(
            src_dir.join("models").join("admin_user.rs"),
            "pub struct Model { pub id: i32, pub role: String }",
        )
        .unwrap();
        // Create regular_user.rs with Model
        std::fs::write(
            src_dir.join("models").join("regular_user.rs"),
            "pub struct Model { pub id: i32, pub name: String }",
        )
        .unwrap();

        // With hint "AdminUserSchema" - should find admin_user.rs
        // "AdminUserSchema" -> prefix "adminuser" -> matches "admin_user.rs" (normalized: "adminuser")
        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("AdminUserSchema"));
        assert!(
            result.is_some(),
            "AdminUserSchema hint should match admin_user.rs"
        );
        let (metadata, module_path) = result.unwrap();
        assert!(
            metadata.definition.contains("role"),
            "Should be admin_user Model with role field"
        );
        assert!(
            module_path.contains(&"admin_user".to_string()),
            "Module path should contain 'admin_user'"
        );

        // With hint "RegularUserSchema" - should find regular_user.rs
        let result_regular =
            find_struct_by_name_in_all_files(src_dir, "Model", Some("RegularUserSchema"));
        assert!(
            result_regular.is_some(),
            "RegularUserSchema hint should match regular_user.rs"
        );
        let (metadata_regular, _) = result_regular.unwrap();
        assert!(
            metadata_regular.definition.contains("name"),
            "Should be regular_user Model with name field"
        );
    }

    // ============================================================
    // Coverage tests for find_struct_from_schema_path
    // ============================================================

    #[test]
    fn test_find_struct_from_schema_path_empty_string() {
        // Tests: Empty path string -> returns None
        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result = find_struct_from_schema_path("");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Empty path should return None");
    }

    #[test]
    fn test_find_struct_from_schema_path_no_module() {
        // Tests: Path with only struct name (no module) -> returns None
        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // Only "Schema" with no module path - after filtering crate/self/super, module_segments is empty
        let result = find_struct_from_schema_path("crate::Schema");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Path with no module should return None");
    }

    #[test]
    #[serial]
    fn test_find_struct_from_schema_path_with_non_struct_items() {
        // Tests: File contains non-struct items that get skipped
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        let content = r"
pub enum NotStruct { A, B }
pub fn not_struct() {}
pub struct Target { pub id: i32 }
pub const NOT_STRUCT: i32 = 1;
";
        std::fs::write(models_dir.join("item.rs"), content).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result = find_struct_from_schema_path("crate::models::item::Target");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_some(), "Should find Target struct");
        assert!(result.unwrap().definition.contains("Target"));
    }

    // ============================================================
    // Coverage tests for find_model_from_schema_path
    // ============================================================

    #[test]
    fn test_find_model_from_schema_path_empty_after_filter() {
        // Tests: After filtering "Schema" and other keywords, segments is empty
        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // Only "Schema" - after filtering, empty
        let result = find_model_from_schema_path("Schema");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Empty segments should return None");
    }

    #[test]
    fn test_find_model_from_schema_path_no_module() {
        // Tests: After filtering crate/self/super, module_segments is empty
        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        let temp_dir = TempDir::new().unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // "crate::Schema" - after filtering "Schema" and "crate", module_segments is empty
        let result = find_model_from_schema_path("crate::Schema");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "No module segments should return None");
    }

    #[test]
    #[serial]
    fn test_find_model_from_schema_path_success() {
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        let content = "pub struct Model { pub id: i32, pub name: String }";
        std::fs::write(models_dir.join("user.rs"), content).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result = find_model_from_schema_path("crate::models::user::Schema");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_some(), "Should find Model");
        assert!(result.unwrap().definition.contains("Model"));
    }

    #[test]
    #[serial]
    fn test_find_struct_disambiguation_fallback_contains() {
        // Tests: No exact match, but fallback "contains" finds exactly one match
        // Tests for fallback contains path
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        std::fs::create_dir(src_dir.join("models")).unwrap();
        // No file named exactly "special.rs", but "special_item.rs" contains "special"
        std::fs::write(
            src_dir.join("models").join("special_item.rs"),
            "pub struct Model { pub special_field: i32 }",
        )
        .unwrap();
        // Another file that doesn't match
        std::fs::write(
            src_dir.join("models").join("regular.rs"),
            "pub struct Model { pub regular_field: String }",
        )
        .unwrap();

        // With hint "SpecialSchema" -> prefix "special"
        // No exact match (no "special.rs"), but "special_item.rs" contains "special"
        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("SpecialSchema"));
        assert!(
            result.is_some(),
            "SpecialSchema hint should match special_item.rs via contains fallback"
        );
        let (metadata, module_path) = result.unwrap();
        assert!(
            metadata.definition.contains("special_field"),
            "Should be special_item Model with special_field"
        );
        assert!(
            module_path.contains(&"special_item".to_string()),
            "Module path should contain 'special_item'"
        );
    }

    // ============================================================
    // Tests for find_fk_column_from_target_entity
    // ============================================================

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_success() {
        // Tests: Full success path - find FK column from target entity
        // Full success path
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create notification.rs with a BelongsTo relation that has relation_enum matching via_rel
        let notification_model = r#"
pub struct Model {
    pub id: i32,
    pub message: String,
    pub target_user_id: i32,
    #[sea_orm(belongs_to = "super::user::Entity", from = "target_user_id", to = "id", relation_enum = "TargetUser")]
    pub target_user: BelongsTo<super::user::Entity>,
}
"#;
        std::fs::write(models_dir.join("notification.rs"), notification_model).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::notification::Schema", "TargetUser");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert_eq!(
            result,
            Some("target_user_id".to_string()),
            "Should find FK column 'target_user_id'"
        );
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_mod_rs() {
        // Tests: Find FK column from mod.rs file
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models").join("notification");
        std::fs::create_dir_all(&models_dir).unwrap();

        let notification_model = r#"
pub struct Model {
    pub id: i32,
    pub sender_id: i32,
    #[sea_orm(belongs_to = "super::super::user::Entity", from = "sender_id", to = "id", relation_enum = "Sender")]
    pub sender: BelongsTo<super::super::user::Entity>,
}
"#;
        std::fs::write(models_dir.join("mod.rs"), notification_model).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::notification::Schema", "Sender");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert_eq!(
            result,
            Some("sender_id".to_string()),
            "Should find FK column from mod.rs"
        );
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_empty_module_segments() {
        // Tests: Empty module segments return None
        let temp_dir = TempDir::new().unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // After filtering "crate", "Schema", segments is empty
        let result = find_fk_column_from_target_entity("crate::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Empty module segments should return None");
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_file_not_found() {
        // Tests: File does not exist -> continue, then return None
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        std::fs::create_dir_all(&src_dir).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // Path to non-existent file
        let result =
            find_fk_column_from_target_entity("crate::models::nonexistent::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Non-existent file should return None");
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_unparseable_file() {
        // Tests: File cannot be parsed -> returns None
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create unparseable file
        std::fs::write(models_dir.join("broken.rs"), "this is not valid rust {{{{").unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::broken::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Unparseable file should return None");
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_no_model_struct() {
        // Tests: File exists but has no Model struct
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create file without Model struct
        let content = r"
pub struct SomethingElse {
    pub id: i32,
}
pub enum Status { Active, Inactive }
";
        std::fs::write(models_dir.join("nomodel.rs"), content).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::nomodel::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(
            result.is_none(),
            "File without Model struct should return None"
        );
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_no_matching_relation_enum() {
        // Tests: Model exists but no field matches the via_rel
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create model with different relation_enum
        let model = r#"
pub struct Model {
    pub id: i32,
    pub user_id: i32,
    #[sea_orm(belongs_to = "super::user::Entity", from = "user_id", to = "id", relation_enum = "Author")]
    pub user: BelongsTo<super::user::Entity>,
}
"#;
        std::fs::write(models_dir.join("comment.rs"), model).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // Search for "TargetUser" but only "Author" exists
        let result =
            find_fk_column_from_target_entity("crate::models::comment::Schema", "TargetUser");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(
            result.is_none(),
            "Non-matching relation_enum should return None"
        );
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_tuple_struct() {
        // Tests: Model is a tuple struct (not named fields) -> skip
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create tuple struct Model
        let model = "pub struct Model(i32, String);";
        std::fs::write(models_dir.join("tuple.rs"), model).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::tuple::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_none(), "Tuple struct Model should return None");
    }

    #[test]
    #[serial]
    fn test_find_fk_column_from_target_entity_field_no_from_attr() {
        // Tests: Field matches relation_enum but has no `from` attribute
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create model with relation_enum but no `from` attribute
        let model = r#"
pub struct Model {
    pub id: i32,
    pub user_id: i32,
    #[sea_orm(belongs_to = "super::user::Entity", to = "id", relation_enum = "TargetUser")]
    pub user: BelongsTo<super::user::Entity>,
}
"#;
        std::fs::write(models_dir.join("nofrom.rs"), model).unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let result =
            find_fk_column_from_target_entity("crate::models::nofrom::Schema", "TargetUser");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        // extract_belongs_to_from_field returns None when no `from` attr
        assert!(
            result.is_none(),
            "Field without 'from' attribute should return None"
        );
    }

    // ============================================================
    // Coverage tests for find_struct_by_name_in_all_files (candidate/rest paths)
    // ============================================================

    #[test]
    #[serial]
    fn test_find_struct_candidate_unparseable_file() {
        // Tests line 145: candidate file fails to parse -> continue to next candidate
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // user.rs matches hint prefix "user" (candidate), contains "Model" text, but won't parse
        std::fs::write(
            src_dir.join("user.rs"),
            "pub struct Model {{{{ broken syntax",
        )
        .unwrap();

        // valid.rs contains Model and parses fine (goes to rest since filename doesn't match prefix)
        std::fs::write(src_dir.join("valid.rs"), "pub struct Model { pub id: i32 }").unwrap();

        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));

        assert!(
            result.is_some(),
            "Should find Model in valid.rs after skipping unparseable candidate user.rs"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_exact_filename_disambiguation() {
        // Tests lines 168-170: multiple candidates found, exact filename match disambiguates
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // user.rs: exact match (normalize_name("user") == prefix "user")
        std::fs::write(src_dir.join("user.rs"), "pub struct Model { pub id: i32 }").unwrap();

        // user_extended.rs: contains-match only (normalize_name("user_extended") = "userextended" != "user")
        std::fs::write(
            src_dir.join("user_extended.rs"),
            "pub struct Model { pub name: String }",
        )
        .unwrap();

        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));

        assert!(result.is_some(), "Should resolve via exact filename match");
        let (metadata, _) = result.unwrap();
        assert!(
            metadata.definition.contains("id"),
            "Should return user.rs Model (with id field)"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_no_match_in_candidates_falls_to_rest() {
        // Tests line 189: candidates have no struct match -> rs_files = rest -> full scan finds it
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // user.rs is a candidate (filename matches "user" prefix) but has no struct Model
        // Must contain "Model" text for get_struct_candidates to include it
        std::fs::write(
            src_dir.join("user.rs"),
            "pub struct Other { pub x: i32 } // Model ref",
        )
        .unwrap();

        // data.rs is in rest (filename "data" doesn't contain "user"), has struct Model
        std::fs::write(src_dir.join("data.rs"), "pub struct Model { pub id: i32 }").unwrap();

        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));

        assert!(
            result.is_some(),
            "Should find Model in data.rs after candidates had no match"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_full_scan_unparseable_file() {
        // Tests line 197: full-scan file fails to parse -> continue to next file
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path();

        // user.rs is candidate but no struct Model
        std::fs::write(
            src_dir.join("user.rs"),
            "pub struct Other { pub x: i32 } // Model",
        )
        .unwrap();

        // broken.rs is rest, contains "Model" text but won't parse
        std::fs::write(src_dir.join("broken.rs"), "Model unparseable {{{{{").unwrap();

        // valid.rs is rest, has struct Model
        std::fs::write(src_dir.join("valid.rs"), "pub struct Model { pub id: i32 }").unwrap();

        let result = find_struct_by_name_in_all_files(src_dir, "Model", Some("UserSchema"));

        assert!(
            result.is_some(),
            "Should find Model in valid.rs after skipping unparseable broken.rs in rest"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_from_path_qualified_module_path() {
        // Exercises the candidate_file_paths call (line 82) with a fully qualified path
        // where the file exists at the expected module location
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create user.rs at the expected module path location
        std::fs::write(
            models_dir.join("user.rs"),
            "pub struct Model { pub id: i32, pub name: String }",
        )
        .unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // Use a fully qualified path: crate::models::user::Model
        // This ensures module_segments = ["models", "user"] (non-empty after filtering "crate")
        // which reaches line 82: candidate_file_paths(&src_dir, &module_segments)
        let ty: syn::Type = syn::parse_str("crate::models::user::Model").unwrap();
        let result = find_struct_from_path(&ty, None);

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(
            result.is_some(),
            "Should find Model struct via qualified path"
        );
        let (metadata, module_path) = result.unwrap();
        assert!(
            metadata.definition.contains("Model"),
            "Definition should contain Model"
        );
        assert_eq!(
            module_path,
            vec!["crate", "models", "user"],
            "Module path should be inferred from type path"
        );
    }

    #[test]
    #[serial]
    fn test_find_struct_from_path_mod_rs_variant() {
        // Exercises candidate_file_paths with the mod.rs pattern
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models").join("user");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create mod.rs instead of user.rs
        std::fs::write(
            models_dir.join("mod.rs"),
            "pub struct Model { pub id: i32, pub email: String }",
        )
        .unwrap();

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let ty: syn::Type = syn::parse_str("crate::models::user::Model").unwrap();
        let result = find_struct_from_path(&ty, None);

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(result.is_some(), "Should find Model struct via mod.rs path");
        let (metadata, _) = result.unwrap();
        assert!(
            metadata.definition.contains("email"),
            "Should find the correct Model with email field"
        );
    }

    #[test]
    #[serial]
    fn test_find_fk_column_parse_struct_cached_failure() {
        // Exercises line 334: get_struct_definition succeeds but parse_struct_cached fails.
        // We inject an invalid struct definition string into the cache so that
        // parse_struct_cached returns Err, triggering the `continue` branch.
        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        let models_dir = src_dir.join("models");
        std::fs::create_dir_all(&models_dir).unwrap();

        // Create a real file so the file_path exists (candidate_file_paths will find it)
        let model_file = models_dir.join("item.rs");
        std::fs::write(&model_file, "pub struct Model { pub id: i32 }").unwrap();

        // Inject a CORRUPT definition for "Model" at this path — syn::parse_str will fail
        crate::schema_macro::file_cache::inject_struct_definition_for_test(
            &model_file,
            "Model",
            "not valid rust {{ struct }}",
        );

        let original = std::env::var("CARGO_MANIFEST_DIR").ok();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        // This should trigger: get_struct_definition -> Some(corrupt) -> parse_struct_cached -> Err -> continue
        let result =
            find_fk_column_from_target_entity("crate::models::item::Schema", "SomeRelation");

        unsafe {
            if let Some(dir) = original {
                std::env::set_var("CARGO_MANIFEST_DIR", dir);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }

        assert!(
            result.is_none(),
            "Should return None when struct definition fails to parse"
        );
    }
}