clawspec-core 0.4.4

Core library for generating OpenAPI specifications from tests
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
use std::any::{TypeId, type_name};
use std::collections::HashSet;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::sync::LazyLock;

use indexmap::{IndexMap, IndexSet};
use utoipa::ToSchema;
use utoipa::openapi::{Ref, RefOr, Schema};

/// Set of primitive type names that should be inlined rather than referenced
static PRIMITIVE_TYPES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    HashSet::from([
        "bool", "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128",
        "usize", "f32", "f64", "String", "str", "binary",
    ])
});

/// Computes a schema reference locally without accessing shared state.
///
/// This enables fire-and-forget schema registration via channels by allowing
/// callers to compute the schema reference before sending the message.
///
/// - Primitive types are inlined (return `RefOr::T`)
/// - Complex types are referenced (return `RefOr::Ref`)
pub(in crate::client) fn compute_schema_ref<T>() -> RefOr<Schema>
where
    T: ToSchema + 'static,
{
    let name = T::name();
    if PRIMITIVE_TYPES.contains(name.as_ref()) {
        T::schema()
    } else {
        RefOr::Ref(Ref::from_schema_name(name.as_ref()))
    }
}

#[derive(Clone, Default)]
pub(in crate::client) struct Schemas {
    entries: IndexMap<TypeId, SchemaEntry>,
    resolved_names: std::collections::HashMap<TypeId, String>,
    /// Schemas transitively reachable from a registered type's nested fields/variants,
    /// discovered via utoipa's `ToSchema::schemas()` recursive walk. Keyed by name rather
    /// than `TypeId` since utoipa's API only exposes the name for these. A `TypeId`-backed
    /// entry with the same name always takes precedence (see `schema_vec`).
    nested: IndexMap<String, RefOr<Schema>>,
}

impl Debug for Schemas {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let names = self
            .entries
            .values()
            .map(|it| it.type_name.as_str())
            .collect::<Vec<_>>();
        f.debug_tuple("Schemas").field(&names).finish()
    }
}

impl Schemas {
    /// Folds nested `(name, schema)` pairs discovered via `ToSchema::schemas()` into the
    /// name-keyed side table. First-write-wins: a name already present (for instance from an
    /// earlier nested walk, or destined to be shadowed by a directly registered type in
    /// `schema_vec`) is left untouched.
    ///
    /// When an already-present name maps to a *different* schema shape, the incoming one is a
    /// genuine short-name collision between two distinct types (utoipa exposes only the name,
    /// not a `TypeId`, for nested schemas, so they cannot be namespaced apart). The first is
    /// kept and a warning is emitted, mirroring the nested-vs-registered path in `schema_vec`.
    fn absorb_nested(&mut self, nested: impl IntoIterator<Item = (String, RefOr<Schema>)>) {
        for (name, schema) in nested {
            match self.nested.entry(name) {
                indexmap::map::Entry::Vacant(vacant) => {
                    vacant.insert(schema);
                }
                indexmap::map::Entry::Occupied(occupied) if *occupied.get() != schema => {
                    tracing::warn!(
                        schema_name = %occupied.key(),
                        "Two distinct nested types resolve to the same schema name with \
                         different shapes; keeping the first. Disambiguate one of them with \
                         #[schema(as = \"module::Type\")]."
                    );
                }
                indexmap::map::Entry::Occupied(_) => {}
            }
        }
    }

    pub(crate) fn add_entry(&mut self, mut entry: SchemaEntry) -> RefOr<Schema> {
        let type_id = entry.id;

        if !self.entries.contains_key(&type_id) {
            self.absorb_nested(std::mem::take(&mut entry.nested));
        }

        // First insert/update the entry
        let _ = self
            .entries
            .entry(type_id)
            .and_modify(|existing| existing.examples.extend(entry.examples.clone()))
            .or_insert(entry);

        // Then resolve name for this type and cache it
        let resolved_name = self.resolve_name_for_type(type_id);

        // Create the reference using the resolved name
        if self.entries[&type_id].should_inline_schema() {
            self.entries[&type_id].schema.clone()
        } else {
            RefOr::Ref(Ref::from_schema_name(&resolved_name))
        }
    }

    fn add_type<T>(&mut self) -> &mut SchemaEntry
    where
        T: ToSchema + 'static,
    {
        let id = TypeId::of::<T>();
        if !self.entries.contains_key(&id) {
            let mut entry = SchemaEntry::of::<T>();
            self.absorb_nested(std::mem::take(&mut entry.nested));
            self.entries.insert(id, entry);
        }
        self.entries
            .get_mut(&id)
            .expect("entry inserted above if it was missing")
    }

    pub(in crate::client) fn add<T>(&mut self) -> RefOr<Schema>
    where
        T: ToSchema + 'static,
    {
        let type_id = TypeId::of::<T>();
        let _ = self.add_type::<T>();

        // Resolve name for this type and cache it
        let resolved_name = self.resolve_name_for_type(type_id);

        // Create the reference using the resolved name
        if self.entries[&type_id].should_inline_schema() {
            self.entries[&type_id].schema.clone()
        } else {
            RefOr::Ref(Ref::from_schema_name(&resolved_name))
        }
    }

    pub(in crate::client) fn add_example<T>(
        &mut self,
        example: impl Into<serde_json::Value>,
    ) -> RefOr<Schema>
    where
        T: ToSchema + 'static,
    {
        let example = example.into();
        let type_id = TypeId::of::<T>();
        let entry = self.add_type::<T>();
        entry.examples.insert(example);

        // Resolve name for this type and cache it
        let resolved_name = self.resolve_name_for_type(type_id);

        // Create the reference using the resolved name
        if self.entries[&type_id].should_inline_schema() {
            self.entries[&type_id].schema.clone()
        } else {
            RefOr::Ref(Ref::from_schema_name(&resolved_name))
        }
    }

    /// Add an example to a schema by TypeId (creates entry if not exists).
    ///
    /// This method is used by the channel-based collection system where
    /// the type information is passed as TypeId rather than generic parameters.
    pub(in crate::client) fn add_example_by_id(
        &mut self,
        type_id: TypeId,
        type_name: &str,
        example: serde_json::Value,
    ) {
        if let Some(entry) = self.entries.get_mut(&type_id) {
            entry.examples.insert(example);
        } else {
            tracing::warn!(
                type_name = %type_name,
                "Attempted to add example for unregistered type"
            );
        }
    }

    /// Resolves the unique name for a given TypeId, handling conflicts
    fn resolve_name_for_type(&mut self, target_type_id: TypeId) -> String {
        // Check if we already resolved this type's name
        if let Some(cached_name) = self.resolved_names.get(&target_type_id) {
            return cached_name.clone();
        }

        let target_entry = &self.entries[&target_type_id];
        let base_name = &target_entry.name;

        // Count conflicts
        let conflicts: Vec<_> = self
            .entries
            .values()
            .filter(|entry| !entry.should_inline_schema() && &entry.name == base_name)
            .collect();

        let resolved_name = if conflicts.len() <= 1 {
            // No conflict, use the original name
            base_name.clone()
        } else {
            // Conflict detected - generate unique name using type path
            let type_parts: Vec<&str> = target_entry
                .type_name
                .split("::")
                .filter(|part| !part.is_empty() && !Self::is_filtered_path_part(part))
                .collect();

            if type_parts.len() >= 2 {
                // Use the last two parts for namespace (e.g., "module::Type")
                format!("{}_{}", type_parts[type_parts.len() - 2], base_name)
            } else {
                // Fallback: use a more readable hash-based suffix
                let mut hasher = DefaultHasher::new();
                target_type_id.hash(&mut hasher);
                let hash = hasher.finish();
                let fallback_name = format!("{base_name}_{:x}", hash & 0xFFFF);

                // Warn about fallback naming for debugging purposes
                tracing::warn!(
                    type_name = %target_entry.type_name,
                    base_name = %base_name,
                    fallback_name = %fallback_name,
                    "Schema conflict resolved using hash-based fallback naming. \
                     Consider using more specific module structure for better naming."
                );

                fallback_name
            }
        };

        // Cache the resolved name
        self.resolved_names
            .insert(target_type_id, resolved_name.clone());
        resolved_name
    }

    /// Merges another schema collection into this one.
    ///
    /// This function implements the core schema merge logic that handles
    /// combining schemas from multiple API test calls.
    ///
    /// # Merge Strategy
    ///
    /// - **Type Identity**: Schemas are identified by Rust `TypeId`
    /// - **Type Safety**: Same Rust type always maps to same OpenAPI schema
    /// - **Example Collection**: Examples from both schemas are combined
    /// - **Schema Overwrite**: New schema overwrites existing (same TypeId)
    ///
    /// # Performance Characteristics
    ///
    /// - **Time Complexity**: O(n) where n is the number of schemas to merge
    /// - **Space Complexity**: O(1) additional space (moves entries, doesn't copy)
    /// - **Memory Efficiency**: Direct insertion by TypeId for optimal performance
    ///
    /// # Arguments
    ///
    /// * `other` - The schema collection to merge into this one
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Internal usage - not exposed in public API
    /// let mut schemas1 = Schemas::default();
    /// let mut schemas2 = Schemas::default();
    ///
    /// // schemas1 has User schema with example1
    /// // schemas2 has User schema with example2
    /// schemas1.merge(schemas2);
    /// // Result: schemas1 has User schema with both examples
    /// ```
    pub(in crate::client) fn merge(&mut self, other: Self) {
        // Collect schema names that might be affected by conflicts
        let mut potentially_affected_names = std::collections::HashSet::new();

        for (type_id, entry) in &other.entries {
            // If this name already exists in our collection, it might create conflicts
            if self
                .entries
                .values()
                .any(|existing| existing.name == entry.name && !existing.should_inline_schema())
            {
                potentially_affected_names.insert(entry.name.clone());
            }

            self.entries
                .entry(*type_id)
                .and_modify(|existing| existing.examples.extend(entry.examples.clone()))
                .or_insert(entry.clone());
        }

        // Selectively invalidate cache only for potentially conflicted schemas
        if !potentially_affected_names.is_empty() {
            self.resolved_names.retain(|type_id, _| {
                if let Some(entry) = self.entries.get(type_id) {
                    !potentially_affected_names.contains(&entry.name)
                } else {
                    false // Remove if entry no longer exists
                }
            });
        }

        self.absorb_nested(other.nested);
    }

    pub(in crate::client) fn schema_vec(&self) -> Vec<(String, RefOr<Schema>)> {
        let mut result = vec![];

        // First, identify all non-primitive entries and detect conflicts
        let non_primitive_entries: Vec<_> = self
            .entries
            .iter()
            .filter(|(_, entry)| !entry.should_inline_schema())
            .collect();

        // Count name occurrences to detect conflicts
        let mut name_counts = std::collections::HashMap::<String, u32>::new();
        for (_, entry) in &non_primitive_entries {
            *name_counts.entry(entry.name.clone()).or_insert(0) += 1;
        }

        // Schemas already provided by a directly registered type; these take precedence
        // over a same-named schema discovered only through a nested `schemas()` walk. The
        // same Rust type commonly gets discovered both ways (e.g. it's nested in one
        // response and also used directly as another endpoint's body) - that's expected
        // and produces an identical schema body, so it's only worth a warning when the
        // bodies actually differ (a genuine short-name collision between distinct types).
        //
        // Keyed by the bare `name`, this map is only meaningful for names that occupy the
        // bare slot in the output - i.e. `name_counts[name] == 1`. When several registered
        // types share a short name they are emitted under namespaced names (`module_Foo`),
        // so a same-named nested schema no longer collides and must be appended (see below).
        let registered_schemas: std::collections::HashMap<&str, &RefOr<Schema>> =
            non_primitive_entries
                .iter()
                .map(|(_, entry)| (entry.name.as_str(), &entry.schema))
                .collect();

        // Generate resolved names without cloning the entire structure
        for (type_id, entry) in non_primitive_entries {
            let resolved_name =
                self.resolve_schema_name(*type_id, &entry.name, &entry.type_name, &name_counts);
            let schema = entry.schema.clone();
            result.push((resolved_name, schema));
        }

        // Append schemas transitively discovered via nested ToSchema::schemas() walks.
        for (name, schema) in &self.nested {
            // A directly-registered type only shadows this nested name when it actually
            // occupies the bare slot in the output. If several registered types share the
            // short name they are namespaced instead, leaving it free for the nested schema.
            let shadows_bare_name = name_counts.get(name.as_str()).copied().unwrap_or(0) == 1;
            match registered_schemas.get(name.as_str()) {
                Some(registered_schema) if shadows_bare_name && *registered_schema == schema => {
                    continue;
                }
                Some(_) if shadows_bare_name => {
                    tracing::warn!(
                        schema_name = %name,
                        "Nested schema name collides with a directly registered schema of \
                         the same name but a different shape; keeping the directly \
                         registered one."
                    );
                    continue;
                }
                _ => result.push((name.clone(), schema.clone())),
            }
        }

        result
    }

    /// Resolves schema name for a specific entry without requiring mutable access
    fn resolve_schema_name(
        &self,
        type_id: TypeId,
        base_name: &str,
        type_name: &str,
        name_counts: &std::collections::HashMap<String, u32>,
    ) -> String {
        // Check cache first
        if let Some(cached_name) = self.resolved_names.get(&type_id) {
            return cached_name.clone();
        }

        // If no conflict, use original name
        if name_counts.get(base_name).copied().unwrap_or(0) <= 1 {
            return base_name.to_string();
        }

        // Conflict detected - generate unique name using type path
        let type_parts: Vec<&str> = type_name
            .split("::")
            .filter(|part| !part.is_empty() && !Self::is_filtered_path_part(part))
            .collect();

        if type_parts.len() >= 2 {
            // Use the last two parts for namespace (e.g., "module::Type")
            format!("{}_{}", type_parts[type_parts.len() - 2], base_name)
        } else {
            // Fallback: use a more readable hash-based suffix
            use std::collections::hash_map::DefaultHasher;
            use std::hash::{Hash, Hasher};
            let mut hasher = DefaultHasher::new();
            type_id.hash(&mut hasher);
            let hash = hasher.finish();
            let fallback_name = format!("{base_name}_{:x}", hash & 0xFFFF);

            // Warn about fallback naming for debugging purposes
            tracing::warn!(
                type_name = %type_name,
                base_name = %base_name,
                fallback_name = %fallback_name,
                "Schema conflict resolved using hash-based fallback naming. \
                 Consider using more specific module structure for better naming."
            );

            fallback_name
        }
    }

    /// Checks if a path part should be filtered out from namespace generation
    fn is_filtered_path_part(part: &str) -> bool {
        // Filter out common test-related and internal modules
        matches!(
            part,
            "tests" | "test" | "_test" | "testing" | "internal" | "private"
        )
    }
}

#[derive(Clone, derive_more::Display, derive_more::Debug)]
#[display("[{id:?}] {name}")]
pub(in crate::client) struct SchemaEntry {
    #[debug(ignore)]
    pub(in crate::client) id: TypeId,
    pub(in crate::client) type_name: String,
    pub(in crate::client) name: String,
    #[debug(ignore)]
    pub(in crate::client) schema: RefOr<Schema>,
    pub(in crate::client) examples: IndexSet<serde_json::Value>,
    /// Schemas transitively reachable from this type's fields/variants, discovered via
    /// utoipa's `ToSchema::schemas()` recursive walk. Only meaningful the first time this
    /// entry is inserted into a `Schemas` collection; consumed there (see
    /// `Schemas::absorb_nested`).
    #[debug(ignore)]
    pub(in crate::client) nested: Vec<(String, RefOr<Schema>)>,
}

impl SchemaEntry {
    pub(crate) fn of<T>() -> Self
    where
        T: ToSchema + 'static,
    {
        let id = TypeId::of::<T>();
        let name = T::name();
        let type_name = type_name::<T>();
        let mut nested = Vec::new();
        T::schemas(&mut nested);
        Self {
            id,
            type_name: type_name.to_string(),
            name: name.to_string(),
            schema: T::schema(),
            examples: IndexSet::default(),
            nested,
        }
    }

    /// Creates a generic schema entry for raw binary data.
    ///
    /// This is used when we don't have a specific Rust type to generate
    /// a schema from, such as when sending raw bytes with custom content types.
    pub(crate) fn raw_binary() -> Self {
        use utoipa::openapi::{KnownFormat, ObjectBuilder, Schema, SchemaFormat, Type};

        // Create a unique TypeId for raw binary data
        let id = TypeId::of::<Vec<u8>>();
        let type_name = "Vec<u8>";
        let name = "binary";

        // Create a binary schema
        let schema = RefOr::T(Schema::Object(
            ObjectBuilder::new()
                .schema_type(Type::String)
                .format(Some(SchemaFormat::KnownFormat(KnownFormat::Binary)))
                .build(),
        ));

        Self {
            id,
            type_name: type_name.to_string(),
            name: name.to_string(),
            schema,
            examples: IndexSet::default(),
            nested: Vec::new(),
        }
    }

    pub(crate) fn add_example(&mut self, example: serde_json::Value) {
        self.examples.insert(example);
    }

    /// Determines if this schema should be inlined (for primitives) or referenced (for complex types)
    fn should_inline_schema(&self) -> bool {
        // Check if the schema name (from T::name()) is a primitive type
        // This works for both direct primitives and wrapper types like DisplayArg<T>
        // since DisplayArg<T> delegates T::name() to the inner type
        PRIMITIVE_TYPES.contains(self.name.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Serialize;
    use utoipa::ToSchema;

    #[derive(Debug, ToSchema, Serialize)]
    struct TestType {
        name: String,
        value: i32,
    }

    #[derive(Debug, ToSchema, Serialize)]
    struct AnotherTestType {
        id: u64,
    }

    #[test]
    fn test_schemas_add_single_type() {
        let mut schemas = Schemas::default();
        let schema_ref = schemas.add::<TestType>();

        // Should return a reference
        assert!(matches!(schema_ref, RefOr::Ref(_)));

        // Should have one schema entry
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
        assert_eq!(schema_vec[0].0, "TestType");
    }

    #[test]
    fn test_schemas_add_captures_nested_types_transitively() {
        #[derive(Debug, ToSchema, Serialize)]
        struct Leaf {
            value: i32,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Mid {
            leaf: Leaf,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Root {
            mid: Mid,
        }

        let mut schemas = Schemas::default();
        // Only the root is registered directly; Mid and Leaf must be discovered via
        // ToSchema::schemas()'s recursive walk.
        schemas.add::<Root>();

        let schema_vec = schemas.schema_vec();
        let names: HashSet<&str> = schema_vec.iter().map(|(name, _)| name.as_str()).collect();
        assert_eq!(
            names,
            HashSet::from(["Root", "Mid", "Leaf"]),
            "expected root and all transitively nested types to be captured"
        );
    }

    #[test]
    fn test_schemas_add_captures_flattened_nested_type() {
        #[derive(Debug, ToSchema, Serialize)]
        struct Inner {
            value: i32,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Outer {
            #[serde(flatten)]
            inner: Inner,
            extra: String,
        }

        let mut schemas = Schemas::default();
        schemas.add::<Outer>();

        let schema_vec = schemas.schema_vec();
        let names: HashSet<&str> = schema_vec.iter().map(|(name, _)| name.as_str()).collect();
        assert!(
            names.contains("Inner"),
            "flattened nested type should still be captured, got {names:?}"
        );
    }

    #[test]
    fn test_schemas_add_captures_enum_variant_payload_types() {
        #[derive(Debug, ToSchema, Serialize)]
        struct Created {
            id: u64,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Deleted {
            id: u64,
        }

        #[derive(Debug, ToSchema, Serialize)]
        enum Event {
            Created(Created),
            Deleted(Deleted),
        }

        // Constructed so the variants aren't flagged as dead code.
        let _ = Event::Created(Created { id: 1 });
        let _ = Event::Deleted(Deleted { id: 2 });

        let mut schemas = Schemas::default();
        schemas.add::<Event>();

        let schema_vec = schemas.schema_vec();
        let names: HashSet<&str> = schema_vec.iter().map(|(name, _)| name.as_str()).collect();
        assert!(
            names.contains("Created") && names.contains("Deleted"),
            "enum variant payload types should be captured, got {names:?}"
        );
    }

    #[test]
    fn test_schemas_add_terminates_on_recursive_type_with_no_recursion_attribute() {
        // utoipa's own ToSchema::schemas() has no built-in cycle detection: a recursive
        // field (directly or mutually recursive) *must* be annotated with
        // `#[schema(no_recursion)]`, or utoipa itself stack-overflows while walking it -
        // independent of clawspec-core, and identical to what `#[derive(OpenApi)]` +
        // `components(schemas(...))` would do (see
        // https://github.com/juhaku/utoipa/issues/1134). Document that requirement rather
        // than working around it, since there's no way to intervene inside utoipa's opaque
        // recursive call.
        #[derive(Debug, ToSchema, Serialize)]
        struct Node {
            value: i32,
            #[schema(no_recursion)]
            next: Option<Box<Node>>,
        }

        let mut schemas = Schemas::default();
        schemas.add::<Node>();

        let schema_vec = schemas.schema_vec();
        let names: HashSet<&str> = schema_vec.iter().map(|(name, _)| name.as_str()).collect();
        assert_eq!(names, HashSet::from(["Node"]));
    }

    #[test]
    fn test_schema_vec_nested_collision_keeps_registered_shape() {
        // A directly-registered type and a distinct nested-only type share the same short
        // schema name ("Config"). utoipa exposes only the name (no TypeId) for nested schemas,
        // so they cannot be namespaced apart; the registered shape must win and the nested one
        // is dropped (with a warning). A name-set assertion could not catch a wrong *shape*
        // sneaking in under the right name, so this checks the emitted body and the count.
        #[derive(Debug, ToSchema, Serialize)]
        struct Config {
            timeout_ms: u64,
        }

        // Different type, same default short name ("Config"), reachable only as a nested field.
        mod nested_mod {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct Config {
                retries: String,
            }
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Root {
            config: nested_mod::Config,
        }

        let mut schemas = Schemas::default();
        schemas.add::<Config>();
        schemas.add::<Root>();

        let schema_vec = schemas.schema_vec();
        let config_entries: Vec<_> = schema_vec
            .iter()
            .filter(|(name, _)| name == "Config")
            .collect();
        assert_eq!(
            config_entries.len(),
            1,
            "the colliding short name must appear exactly once, got {schema_vec:?}"
        );
        assert_eq!(
            &config_entries[0].1,
            &<Config as utoipa::PartialSchema>::schema(),
            "the directly-registered Config shape must take precedence over the nested one"
        );
    }

    #[test]
    fn test_schemas_merge_absorbs_nested_schemas() {
        // `merge` must carry over the name-keyed nested table, not just the TypeId entries.
        // Every other merge test uses primitive-only types, so this is the only coverage of
        // schemas discovered transitively arriving through the merge path (e.g. complex
        // struct-valued parameters).
        #[derive(Debug, ToSchema, Serialize)]
        struct Leaf {
            value: i32,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Mid {
            leaf: Leaf,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Root {
            mid: Mid,
        }

        let mut source = Schemas::default();
        source.add::<Root>();

        let mut target = Schemas::default();
        target.merge(source);

        let schema_vec = target.schema_vec();
        let names: HashSet<&str> = schema_vec.iter().map(|(name, _)| name.as_str()).collect();
        assert!(
            names.is_superset(&HashSet::from(["Root", "Mid", "Leaf"])),
            "merge must carry over transitively nested schemas, got {names:?}"
        );
    }

    #[test]
    fn test_schema_vec_type_registered_and_nested_appears_once() {
        // The common, benign case: the same Rust type is both registered directly and
        // discovered as a nested field. It shares a TypeId, so both discoveries yield an
        // identical shape; the nested duplicate must be dropped, leaving exactly one entry.
        #[derive(Debug, ToSchema, Serialize)]
        struct Mid {
            value: i32,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Root {
            mid: Mid,
        }

        let mut schemas = Schemas::default();
        schemas.add::<Root>();
        schemas.add::<Mid>();

        let mid_count = schemas
            .schema_vec()
            .iter()
            .filter(|(name, _)| name == "Mid")
            .count();
        assert_eq!(
            mid_count, 1,
            "a type registered directly and discovered nested must appear exactly once"
        );
    }

    #[test]
    fn test_schemas_add_with_example() {
        let mut schemas = Schemas::default();
        let test_example = serde_json::json!({"name": "test", "value": 42});

        let schema_ref = schemas.add_example::<TestType>(test_example.clone());

        matches!(schema_ref, RefOr::Ref(_));

        // Verify the example was added (we can't directly access it but we can check it doesn't panic)
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
    }

    #[test]
    fn test_schemas_add_same_type_twice_returns_same_entry() {
        let mut schemas = Schemas::default();

        schemas.add::<TestType>();
        schemas.add::<TestType>();

        // Should still only have one entry
        assert_eq!(schemas.entries.len(), 1);
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
    }

    #[test]
    fn test_schemas_add_different_types() {
        let mut schemas = Schemas::default();

        schemas.add::<TestType>();
        schemas.add::<AnotherTestType>();

        // Should have two entries
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 2);

        let names = schema_vec
            .iter()
            .map(|(name, _)| name.as_str())
            .collect::<Vec<&str>>();
        assert!(names.contains(&"TestType"));
        assert!(names.contains(&"AnotherTestType"));
    }

    #[test]
    fn test_schemas_merge() {
        let mut schemas1 = Schemas::default();
        schemas1.add::<TestType>();

        let mut schemas2 = Schemas::default();
        schemas2.add::<AnotherTestType>();

        schemas1.merge(schemas2);

        // Should have both types
        let schema_vec = schemas1.schema_vec();
        assert_eq!(schema_vec.len(), 2);
    }

    #[test]
    fn test_schemas_merge_with_conflicts_and_examples() {
        // Test merge behavior with conflicting schema names and example collection
        #[derive(Debug, ToSchema, Serialize)]
        struct User {
            id: u64,
            name: String,
        }

        mod api_v1 {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct User {
                user_id: String,
                email: String,
            }
        }

        // Create first collection with User and examples
        let mut schemas1 = Schemas::default();
        let example1 = serde_json::json!({"id": 1, "name": "Alice"});
        schemas1.add_example::<User>(example1.clone());

        // Create second collection with different User type and examples
        let mut schemas2 = Schemas::default();
        let example2 = serde_json::json!({"user_id": "abc123", "email": "alice@example.com"});
        schemas2.add_example::<api_v1::User>(example2.clone());

        // Also add another example for the same User type to first collection
        let example3 = serde_json::json!({"id": 2, "name": "Bob"});
        schemas1.add_example::<User>(example3.clone());

        // Merge schemas2 into schemas1
        schemas1.merge(schemas2);

        // Should have both User types
        assert_eq!(schemas1.entries.len(), 2);

        // Get schema vector - conflicts should be resolved
        let schema_vec = schemas1.schema_vec();
        assert_eq!(schema_vec.len(), 2, "Should have both User schemas");

        // Names should be unique
        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();
        let mut unique_names = std::collections::HashSet::new();
        for name in &names {
            assert!(
                unique_names.insert(*name),
                "Schema name '{name}' should be unique"
            );
        }

        // Should have one namespaced name
        let has_namespaced = names.iter().any(|name| name.contains("api_v1_User"));
        assert!(
            has_namespaced,
            "Should have a namespaced User schema from api_v1"
        );

        // Verify examples are preserved after merge
        let user_type_id = TypeId::of::<User>();
        let api_v1_user_type_id = TypeId::of::<api_v1::User>();

        let user_entry = &schemas1.entries[&user_type_id];
        assert_eq!(user_entry.examples.len(), 2); // example1 + example3
        assert!(user_entry.examples.contains(&example1));
        assert!(user_entry.examples.contains(&example3));

        let api_v1_user_entry = &schemas1.entries[&api_v1_user_type_id];
        assert_eq!(api_v1_user_entry.examples.len(), 1); // example2
        assert!(api_v1_user_entry.examples.contains(&example2));
    }

    #[test]
    fn test_schema_entry_creation() {
        let entry = SchemaEntry::of::<TestType>();

        assert_eq!(entry.name, "TestType");
        assert_eq!(
            entry.type_name,
            "clawspec_core::client::openapi::schema::tests::TestType"
        );
        assert!(entry.examples.is_empty());
    }

    #[test]
    fn test_schema_entry_add_example() {
        let mut entry = SchemaEntry::of::<TestType>();
        let example = serde_json::json!({"name": "test", "value": 42});

        entry.add_example(example.clone());

        assert_eq!(entry.examples.len(), 1);
        assert!(entry.examples.contains(&example));
    }

    #[test]
    fn test_schema_entry_add_duplicate_example() {
        let mut entry = SchemaEntry::of::<TestType>();
        let example = serde_json::json!({"name": "test", "value": 42});

        entry.add_example(example.clone());
        entry.add_example(example); // Add same example again

        // Should still only have one example (IndexSet deduplicates)
        assert_eq!(entry.examples.len(), 1);
    }

    #[test]
    fn test_schema_entry_reference_creation() {
        let entry = SchemaEntry::of::<TestType>();

        // Test that non-primitive types should be referenced
        assert!(!entry.should_inline_schema());

        // Test schema reference creation
        let schema_ref: RefOr<Schema> = RefOr::Ref(Ref::from_schema_name("TestType"));
        insta::assert_debug_snapshot!(schema_ref, @r##"
        Ref(
            Ref {
                ref_location: "#/components/schemas/TestType",
                description: "",
                summary: "",
            },
        )
        "##);
    }

    #[test]
    fn test_primitive_types_are_inlined() {
        let mut schemas = Schemas::default();

        // Add a primitive type (usize)
        let usize_schema = schemas.add_example::<usize>(42);

        // Should return inline schema, not a reference
        assert!(matches!(usize_schema, RefOr::T(_)));

        // Should NOT be in the components/schemas section
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 0);
    }

    #[test]
    fn test_complex_types_are_referenced() {
        let mut schemas = Schemas::default();

        // Add a complex type
        let complex_schema =
            schemas.add_example::<TestType>(serde_json::json!({"name": "test", "value": 42}));

        // Should return a reference
        assert!(matches!(complex_schema, RefOr::Ref(_)));

        // Should be in the components/schemas section
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
        assert_eq!(schema_vec[0].0, "TestType");
    }

    #[test]
    fn test_mixed_primitive_and_complex_types() {
        let mut schemas = Schemas::default();

        // Add primitive and complex types
        let usize_schema = schemas.add_example::<usize>(42);
        let complex_schema =
            schemas.add_example::<TestType>(serde_json::json!({"name": "test", "value": 42}));

        // Primitive should be inlined
        assert!(matches!(usize_schema, RefOr::T(_)));

        // Complex should be referenced
        assert!(matches!(complex_schema, RefOr::Ref(_)));

        // Only complex type should be in components/schemas
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
        assert_eq!(schema_vec[0].0, "TestType");
    }

    #[test]
    fn test_schema_name_conflicts_are_resolved() {
        // This test verifies that schema name conflicts are properly resolved
        #[derive(Debug, ToSchema, Serialize)]
        struct User {
            id: u64,
            name: String,
        }

        // Different module with same schema name
        mod other_module {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct User {
                user_id: String,
                email: String,
            }
        }

        let mut schemas = Schemas::default();

        // Add both types - they have different TypeIds but same schema name
        let schema1 = schemas.add::<User>();
        let schema2 = schemas.add::<other_module::User>();

        // Both should be referenced (not inlined)
        assert!(matches!(schema1, RefOr::Ref(_)));
        assert!(matches!(schema2, RefOr::Ref(_)));

        // Check the internal storage - should have 2 entries with different TypeIds
        assert_eq!(schemas.entries.len(), 2);

        // Get the schema_vec for OpenAPI output - conflicts should be resolved
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 2, "Should have both schemas");

        // Extract schema names
        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();

        // Verify that names are unique (no conflicts)
        let mut unique_names = std::collections::HashSet::new();
        for name in &names {
            assert!(
                unique_names.insert(*name),
                "Schema name '{name}' should be unique"
            );
        }

        // Should have exactly one name containing "other_module_User" and one with base "User" or namespace
        let has_namespaced = names.iter().any(|name| name.contains("other_module_User"));
        assert!(has_namespaced, "Should have a namespaced User schema");

        println!("Resolved schema names: {names:?}");

        // Verify that references point to the correct unique names
        if let RefOr::Ref(ref_obj) = &schema1 {
            let ref_name = ref_obj
                .ref_location
                .trim_start_matches("#/components/schemas/");
            assert!(
                names.iter().any(|&name| name == ref_name),
                "Reference '{ref_name}' should match a schema name"
            );
        }

        if let RefOr::Ref(ref_obj) = &schema2 {
            let ref_name = ref_obj
                .ref_location
                .trim_start_matches("#/components/schemas/");
            assert!(
                names.iter().any(|&name| name == ref_name),
                "Reference '{ref_name}' should match a schema name"
            );
        }
    }

    #[test]
    fn test_enhanced_example_generation_and_validation() {
        // This test verifies enhanced example handling for schemas
        #[derive(Debug, ToSchema, Serialize)]
        struct Product {
            id: u32,
            name: String,
            price: f64,
        }

        let mut schemas = Schemas::default();

        // Add schema with multiple examples to test example collection
        let example1 = serde_json::json!({"id": 1, "name": "Laptop", "price": 999.99});
        let example2 = serde_json::json!({"id": 2, "name": "Mouse", "price": 29.99});
        let example3 = serde_json::json!({"id": 3, "name": "Keyboard", "price": 89.99});

        // Add the same type multiple times with different examples
        schemas.add_example::<Product>(example1.clone());
        schemas.add_example::<Product>(example2.clone());
        schemas.add_example::<Product>(example3.clone());

        // Should still only have one schema entry (same type)
        assert_eq!(schemas.entries.len(), 1);

        // Get the product entry to verify example collection
        let product_type_id = TypeId::of::<Product>();
        let product_entry = &schemas.entries[&product_type_id];

        // Should have collected all three examples
        assert_eq!(product_entry.examples.len(), 3);
        assert!(product_entry.examples.contains(&example1));
        assert!(product_entry.examples.contains(&example2));
        assert!(product_entry.examples.contains(&example3));

        // Schema should be properly referenced (not inlined)
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 1);
        assert_eq!(schema_vec[0].0, "Product");

        // Test duplicate example deduplication
        schemas.add_example::<Product>(example1.clone()); // Add same example again
        let product_entry = &schemas.entries[&product_type_id];
        assert_eq!(
            product_entry.examples.len(),
            3,
            "Duplicate examples should be deduplicated"
        );
    }

    #[test]
    fn test_fallback_naming_strategy() {
        // Test the fallback naming when type path has insufficient parts
        #[derive(Debug, ToSchema, Serialize)]
        struct SimpleType;

        // Create a type in the root namespace (less than 2 path parts)
        let mut schemas = Schemas::default();

        // Manually create an entry to simulate root-level types
        let simple_entry = SchemaEntry {
            id: TypeId::of::<SimpleType>(),
            type_name: "SimpleType".to_string(), // Root level, no :: separator
            name: "SimpleType".to_string(),
            schema: RefOr::T(utoipa::openapi::Schema::Object(Default::default())),
            examples: IndexSet::default(),
            nested: Vec::new(),
        };

        // Add the same name from another "type" to force conflict
        let conflicting_entry = SchemaEntry {
            id: TypeId::of::<String>(), // Different type, same schema name
            type_name: "String".to_string(),
            name: "SimpleType".to_string(), // Same name as above!
            schema: RefOr::T(utoipa::openapi::Schema::Object(Default::default())),
            examples: IndexSet::default(),
            nested: Vec::new(),
        };

        schemas.entries.insert(simple_entry.id, simple_entry);
        schemas
            .entries
            .insert(conflicting_entry.id, conflicting_entry);

        // Get schema vector - should use hash-based fallback naming
        let schema_vec = schemas.schema_vec();
        assert_eq!(schema_vec.len(), 2);

        // Both should have unique names, and at least one should use hash-based naming
        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();
        let mut unique_names = std::collections::HashSet::new();
        for name in &names {
            assert!(
                unique_names.insert(*name),
                "Schema name '{name}' should be unique"
            );
        }

        // At least one name should contain a hex hash
        let has_hash_name = names.iter().any(|name| {
            name.contains("_")
                && name
                    .split('_')
                    .next_back()
                    .unwrap_or("")
                    .chars()
                    .all(|c| c.is_ascii_hexdigit())
        });
        assert!(
            has_hash_name,
            "Should have at least one hash-based fallback name"
        );
    }

    #[test]
    fn test_path_filtering_edge_cases() {
        // Test various edge cases in path filtering
        assert!(Schemas::is_filtered_path_part("tests"));
        assert!(Schemas::is_filtered_path_part("test"));
        assert!(Schemas::is_filtered_path_part("_test"));
        assert!(Schemas::is_filtered_path_part("testing"));
        assert!(Schemas::is_filtered_path_part("internal"));
        assert!(Schemas::is_filtered_path_part("private"));

        // These should not be filtered
        assert!(!Schemas::is_filtered_path_part("user"));
        assert!(!Schemas::is_filtered_path_part("api"));
        assert!(!Schemas::is_filtered_path_part("v1"));
        assert!(!Schemas::is_filtered_path_part("service"));
    }

    #[test]
    fn test_selective_cache_invalidation() {
        // Test that cache invalidation only affects conflicted schemas
        #[derive(Debug, ToSchema, Serialize)]
        struct User {
            id: u64,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Product {
            name: String,
        }

        mod api_v1 {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct User {
                user_id: String,
            }
        }

        // Create first schema collection
        let mut schemas1 = Schemas::default();
        schemas1.add::<User>();
        schemas1.add::<Product>();

        // Manually populate cache to simulate cached state
        let user_id = TypeId::of::<User>();
        let product_id = TypeId::of::<Product>();
        schemas1.resolved_names.insert(user_id, "User".to_string());
        schemas1
            .resolved_names
            .insert(product_id, "Product".to_string());

        // Create second collection with conflicting User but no Product
        let mut schemas2 = Schemas::default();
        schemas2.add::<api_v1::User>();

        // Before merge, should have 2 cached names
        assert_eq!(schemas1.resolved_names.len(), 2);

        // Merge - should only invalidate User-related cache entries
        schemas1.merge(schemas2);

        // After merge, Product cache should remain, but User cache should be cleared
        // Note: the exact behavior depends on implementation, but cache should be smaller
        assert!(schemas1.resolved_names.len() <= 2);

        // Verify that the schema_vec works correctly after merge
        let schema_vec = schemas1.schema_vec();
        assert_eq!(schema_vec.len(), 3); // User, api_v1_User, Product

        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();
        let mut unique_names = std::collections::HashSet::new();
        for name in &names {
            assert!(
                unique_names.insert(*name),
                "Schema name '{name}' should be unique"
            );
        }
    }

    #[test]
    fn test_merge_behavior_safety() {
        // Test that merge behavior is safe under various conditions
        #[derive(Debug, ToSchema, Serialize)]
        struct User {
            id: u64,
            name: String,
        }

        #[derive(Debug, ToSchema, Serialize)]
        struct Product {
            id: u32,
            name: String,
        }

        mod v1 {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct User {
                user_id: String,
                email: String,
            }
        }

        mod v2 {
            use super::*;

            #[derive(Debug, ToSchema, Serialize)]
            pub struct User {
                uuid: String,
                profile: String,
            }
        }

        // Test 1: Merging empty collections is safe
        let mut empty1 = Schemas::default();
        let empty2 = Schemas::default();
        empty1.merge(empty2);
        assert_eq!(empty1.entries.len(), 0);
        assert_eq!(empty1.resolved_names.len(), 0);

        // Test 2: Merging with conflicting names preserves all data
        let mut schemas1 = Schemas::default();
        let example1 = serde_json::json!({"id": 1, "name": "Alice"});
        schemas1.add_example::<User>(example1.clone());
        schemas1.add::<Product>();

        let mut schemas2 = Schemas::default();
        let example2 = serde_json::json!({"user_id": "abc", "email": "alice@test.com"});
        schemas2.add_example::<v1::User>(example2.clone());

        // Pre-populate cache to test invalidation safety
        let user_id = TypeId::of::<User>();
        let product_id = TypeId::of::<Product>();
        let v1_user_id = TypeId::of::<v1::User>();
        schemas1.resolved_names.insert(user_id, "User".to_string());
        schemas1
            .resolved_names
            .insert(product_id, "Product".to_string());

        // Perform merge
        schemas1.merge(schemas2);

        // Verify all entries are preserved
        assert_eq!(schemas1.entries.len(), 3);
        assert!(schemas1.entries.contains_key(&user_id));
        assert!(schemas1.entries.contains_key(&product_id));
        assert!(schemas1.entries.contains_key(&v1_user_id));

        // Verify examples are preserved
        assert!(schemas1.entries[&user_id].examples.contains(&example1));
        assert!(schemas1.entries[&v1_user_id].examples.contains(&example2));

        // Verify cache invalidation only affects conflicted names
        // Product should not be invalidated as it has no conflicts
        let schema_vec = schemas1.schema_vec();
        assert_eq!(schema_vec.len(), 3);

        // All schema names must be unique
        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();
        let unique_names: std::collections::HashSet<_> = names.iter().collect();
        assert_eq!(
            names.len(),
            unique_names.len(),
            "All schema names must be unique"
        );

        // Test 3: Multiple conflicting merges work correctly
        let mut schemas3 = Schemas::default();
        let example3 = serde_json::json!({"uuid": "uuid123", "profile": "admin"});
        schemas3.add_example::<v2::User>(example3.clone());

        schemas1.merge(schemas3);

        // Should now have 4 schemas: User, Product, v1::User, v2::User
        assert_eq!(schemas1.entries.len(), 4);
        let schema_vec = schemas1.schema_vec();
        assert_eq!(schema_vec.len(), 4);

        // All names still unique
        let names: Vec<&String> = schema_vec.iter().map(|(name, _)| name).collect();
        let unique_names: std::collections::HashSet<_> = names.iter().collect();
        assert_eq!(
            names.len(),
            unique_names.len(),
            "All schema names must remain unique after multiple merges"
        );

        // Examples are preserved across merges
        let v2_user_id = TypeId::of::<v2::User>();
        assert!(schemas1.entries[&v2_user_id].examples.contains(&example3));

        // Test 4: Self-merge is safe (merging identical collections)
        let schemas_copy = schemas1.clone();
        let entries_before = schemas1.entries.len();

        schemas1.merge(schemas_copy);

        // Should have same number of entries (no duplicates)
        assert_eq!(schemas1.entries.len(), entries_before);

        // Examples should be preserved (sets prevent duplicates)
        assert!(schemas1.entries[&user_id].examples.contains(&example1));
        assert!(schemas1.entries[&v1_user_id].examples.contains(&example2));
        assert!(schemas1.entries[&v2_user_id].examples.contains(&example3));
    }
}