reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
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
//! Global model registry for Reinhardt migrations
//!
//! This module provides a Django-like model registration system that allows
//! models to be registered globally and accessed during migration generation.
//!
//! # Django Reference
//! Django's app registry is implemented in `django/apps/registry.py` and provides:
//! - Global model registration via `Apps.register_model()`
//! - Model retrieval via `Apps.get_models()`
//! - Thread-safe access with RwLock
//!
//! See [`ModelMetadata`] for the architecture comparison diagram.

use super::ConstraintDefinition;
use super::autodetector::{FieldState, ModelState};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

#[cfg_attr(doc, aquamarine::aquamarine)]
/// Model metadata for registration
///
/// # Architecture
///
/// This struct mirrors Django's model registration pattern:
///
/// ```mermaid
/// graph LR
///     subgraph Django["Django (Reference)"]
///         Apps["Apps"]
///         Apps --> all_models["all_models"]
///         Apps --> register_model["register_model()"]
///         Apps --> get_models["get_models()"]
///     end
///
///     subgraph Reinhardt["Reinhardt"]
///         ModelRegistry["ModelRegistry"]
///         ModelRegistry --> models["models"]
///         ModelRegistry --> register_model2["register_model()"]
///         ModelRegistry --> get_models2["get_models()"]
///         ModelRegistry --> get_model["get_model()"]
///     end
///
///     Django -.-> Reinhardt
/// ```
#[derive(Debug, Clone)]
pub struct ModelMetadata {
	/// Application label (e.g., "auth", "blog")
	pub app_label: String,
	/// Model name (e.g., "User", "Post")
	pub model_name: String,
	/// Table name (e.g., "auth_user", "blog_post")
	pub table_name: String,
	/// Field definitions
	pub fields: HashMap<String, FieldMetadata>,
	/// Model options (e.g., db_table, ordering)
	pub options: HashMap<String, String>,
	/// ManyToMany relationship definitions
	pub many_to_many_fields: Vec<ManyToManyMetadata>,
	/// Model-level constraints declared via `#[model(unique_together = ...)]`
	/// and other peer-constraint attributes. Field-level `unique = true` is
	/// still synthesized inside `to_model_state()` and not stored here, to
	/// preserve the existing single-field UNIQUE behavior.
	///
	/// Kept private so that adding the field to a previously
	/// externally-constructible struct does not break the public API.
	/// Read via [`Self::constraints`]; write via [`Self::add_constraint`].
	constraints: Vec<ConstraintDefinition>,
}

impl ModelMetadata {
	/// Creates a new instance.
	pub fn new(
		app_label: impl Into<String>,
		model_name: impl Into<String>,
		table_name: impl Into<String>,
	) -> Self {
		Self {
			app_label: app_label.into(),
			model_name: model_name.into(),
			table_name: table_name.into(),
			fields: HashMap::new(),
			options: HashMap::new(),
			many_to_many_fields: Vec::new(),
			constraints: Vec::new(),
		}
	}

	/// Adds field.
	pub fn add_field(&mut self, name: String, field: FieldMetadata) {
		self.fields.insert(name, field);
	}

	/// Sets the option.
	pub fn set_option(&mut self, key: String, value: String) {
		self.options.insert(key, value);
	}

	/// Adds many to many.
	pub fn add_many_to_many(&mut self, m2m: ManyToManyMetadata) {
		self.many_to_many_fields.push(m2m);
	}

	/// Adds a model-level constraint declared via macro attributes
	/// (e.g., `#[model(unique_together = ...)]`).
	pub fn add_constraint(&mut self, constraint: ConstraintDefinition) {
		self.constraints.push(constraint);
	}

	/// Returns model-level constraints registered by the `#[model(...)]`
	/// macro (currently composite UNIQUE from `unique_together`).
	///
	/// Field-level `unique = true` is not included here; it is synthesized
	/// inside [`Self::to_model_state`] from `FieldMetadata` parameters.
	pub fn constraints(&self) -> &[ConstraintDefinition] {
		&self.constraints
	}

	/// Convert to ModelState for migrations
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_db::migrations::model_registry::{ModelMetadata, FieldMetadata};
	/// use reinhardt_db::migrations::FieldType;
	///
	/// let mut metadata = ModelMetadata::new("myapp", "User", "myapp_user");
	/// metadata.add_field(
	///     "email".to_string(),
	///     FieldMetadata::new(FieldType::VarChar(255)).with_param("max_length", "255"),
	/// );
	///
	/// let model_state = metadata.to_model_state();
	/// assert_eq!(model_state.app_label, "myapp");
	/// assert_eq!(model_state.name, "User");
	/// assert!(model_state.has_field("email"));
	/// ```
	pub fn to_model_state(&self) -> ModelState {
		let mut model_state = ModelState::new(&self.app_label, &self.model_name);

		// Set the correct table name from metadata
		// This overrides the default snake_case conversion in ModelState::new
		model_state.table_name = self.table_name.clone();

		// Convert fields
		for (name, field_meta) in &self.fields {
			// Nullability is sourced from `params["null"]` via
			// `FieldMetadata::is_nullable()`. A type-safe field is deferred
			// to the next major version (tracked under `rc-migration`).
			// See #4430 / #4431.
			let mut field_state = FieldState::new(
				name.clone(),
				field_meta.field_type.clone(),
				field_meta.is_nullable(),
			);
			for (key, value) in &field_meta.params {
				field_state.params.insert(key.clone(), value.clone());
			}
			// Set ForeignKey information if present
			if let Some(ref fk_info) = field_meta.foreign_key {
				field_state.foreign_key = Some(fk_info.clone());
			}
			model_state.add_field(field_state);
		}

		// Copy options
		model_state.options = self.options.clone();

		// Generate ForeignKey constraints from fields
		for (field_name, field_meta) in &self.fields {
			if field_meta.foreign_key.is_some() {
				model_state.add_foreign_key_constraint_from_field(field_name);
			}
		}

		// Copy ManyToMany relationship metadata
		model_state.many_to_many_fields = self.many_to_many_fields.clone();

		// Generate Unique constraints from field params
		for (field_name, field_meta) in &self.fields {
			if field_meta.params.get("unique").map(String::as_str) == Some("true") {
				let constraint = ConstraintDefinition {
					name: format!(
						"{}_{}_{}_uniq",
						self.app_label,
						self.model_name.to_lowercase(),
						field_name
					),
					constraint_type: "unique".to_string(),
					fields: vec![field_name.clone()],
					expression: None,
					foreign_key_info: None,
				};
				model_state.constraints.push(constraint);
			}
		}

		// Copy model-level constraints declared via #[model(unique_together = ...)]
		// (and other peer-constraint attributes). These are populated by the
		// derive macro at registration time. See reinhardt-web#4022.
		model_state
			.constraints
			.extend(self.constraints.iter().cloned());

		model_state
	}
}

/// Field metadata for registration
#[derive(Debug, Clone)]
pub struct FieldMetadata {
	/// Field type (e.g., CharField, IntegerField, ForeignKey)
	pub field_type: super::FieldType,
	/// Field parameters (max_length, null, blank, default, etc.)
	///
	/// Nullability is stored under the `"null"` key as `"true"` / `"false"`.
	/// Prefer [`Self::with_nullable`] and [`Self::is_nullable`] over raw
	/// params access. A type-safe replacement is tracked in the next-major
	/// (post-RC) `rc-migration` issue; see #4430 / #4431.
	pub params: HashMap<String, String>,
	/// ForeignKey information if this field is a foreign key
	pub foreign_key: Option<super::autodetector::ForeignKeyInfo>,
}

impl FieldMetadata {
	/// Creates a new instance.
	pub fn new(field_type: super::FieldType) -> Self {
		Self {
			field_type,
			params: HashMap::new(),
			foreign_key: None,
		}
	}

	/// Sets the param and returns self for chaining.
	pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
		self.params.insert(key.into(), value.into());
		self
	}

	/// Sets the nullability and returns self for chaining.
	///
	/// Stored under `params["null"]`; a type-safe field is deferred to the
	/// next major version (tracked under `rc-migration`).
	pub fn with_nullable(mut self, nullable: bool) -> Self {
		self.params.insert("null".to_string(), nullable.to_string());
		self
	}

	/// Returns whether the column is nullable (i.e., `NULL` is allowed).
	///
	/// Reads `params["null"]`; absent or unparseable values default to
	/// `false` (NOT NULL).
	pub fn is_nullable(&self) -> bool {
		self.params
			.get("null")
			.and_then(|v| v.parse::<bool>().ok())
			.unwrap_or(false)
	}

	/// Sets the foreign key and returns self for chaining.
	pub fn with_foreign_key(mut self, foreign_key: super::autodetector::ForeignKeyInfo) -> Self {
		self.foreign_key = Some(foreign_key);
		self
	}
}

/// Relationship metadata for `#[rel]` attributes
///
/// This structure holds metadata about relationships defined on model fields
/// using the `#[rel(...)]` attribute.
#[derive(Debug, Clone)]
pub struct RelationshipMetadata {
	/// Field name
	pub field_name: String,
	/// Relationship type (foreign_key, one_to_one, many_to_many, etc.)
	pub rel_type: String,
	/// Target model (e.g., "User", "auth.User")
	pub to_model: Option<String>,
	/// Related name for reverse accessor
	pub related_name: Option<String>,
	/// Through table name (for ManyToMany)
	pub through_table: Option<String>,
	/// Composite struct name (for additional through table fields)
	pub composite: Option<String>,
	/// Source model app label (for generating Through table foreign keys)
	pub source_app_label: Option<String>,
	/// Source model name (for generating Through table foreign keys)
	pub source_model_name: Option<String>,
}

impl RelationshipMetadata {
	/// Create a new RelationshipMetadata
	pub fn new(field_name: impl Into<String>, rel_type: impl Into<String>) -> Self {
		Self {
			field_name: field_name.into(),
			rel_type: rel_type.into(),
			to_model: None,
			related_name: None,
			through_table: None,
			composite: None,
			source_app_label: None,
			source_model_name: None,
		}
	}

	/// Set target model
	pub fn with_to_model(mut self, to_model: impl Into<String>) -> Self {
		self.to_model = Some(to_model.into());
		self
	}

	/// Set related name
	pub fn with_related_name(mut self, related_name: impl Into<String>) -> Self {
		self.related_name = Some(related_name.into());
		self
	}

	/// Set through table name
	pub fn with_through_table(mut self, through_table: impl Into<String>) -> Self {
		self.through_table = Some(through_table.into());
		self
	}

	/// Set composite struct name
	pub fn with_composite(mut self, composite: impl Into<String>) -> Self {
		self.composite = Some(composite.into());
		self
	}

	/// Set source model information
	pub fn with_source_info(
		mut self,
		app_label: impl Into<String>,
		model_name: impl Into<String>,
	) -> Self {
		self.source_app_label = Some(app_label.into());
		self.source_model_name = Some(model_name.into());
		self
	}

	/// Check if this is a ManyToMany relationship
	pub fn is_many_to_many(&self) -> bool {
		self.rel_type == "many_to_many" || self.rel_type == "polymorphic_many_to_many"
	}
}

/// ManyToMany relationship metadata
///
/// This structure holds specific metadata for ManyToMany relationships,
/// including through table information and custom field names.
#[derive(Debug, Clone, PartialEq)]
pub struct ManyToManyMetadata {
	/// Field name
	pub field_name: String,
	/// Target model name (e.g., "Group", "User")
	pub to_model: String,
	/// Related name for reverse accessor
	pub related_name: Option<String>,
	/// Custom through table name (if specified)
	pub through: Option<String>,
	/// Source field name in through table (defaults to "{source_model}_id")
	pub source_field: Option<String>,
	/// Target field name in through table (defaults to "{target_model}_id")
	pub target_field: Option<String>,
	/// Database constraint prefix
	pub db_constraint_prefix: Option<String>,
}

impl ManyToManyMetadata {
	/// Create a new ManyToManyMetadata
	pub fn new(field_name: impl Into<String>, to_model: impl Into<String>) -> Self {
		Self {
			field_name: field_name.into(),
			to_model: to_model.into(),
			related_name: None,
			through: None,
			source_field: None,
			target_field: None,
			db_constraint_prefix: None,
		}
	}

	/// Set related name
	pub fn with_related_name(mut self, related_name: impl Into<String>) -> Self {
		self.related_name = Some(related_name.into());
		self
	}

	/// Set through table name
	pub fn with_through(mut self, through: impl Into<String>) -> Self {
		self.through = Some(through.into());
		self
	}

	/// Set source field name
	pub fn with_source_field(mut self, source_field: impl Into<String>) -> Self {
		self.source_field = Some(source_field.into());
		self
	}

	/// Set target field name
	pub fn with_target_field(mut self, target_field: impl Into<String>) -> Self {
		self.target_field = Some(target_field.into());
		self
	}

	/// Set database constraint prefix
	pub fn with_db_constraint_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.db_constraint_prefix = Some(prefix.into());
		self
	}
}

/// Global model registry
///
/// This registry is thread-safe and can be accessed from anywhere in the application.
/// Models should register themselves during initialization, typically via derive macros.
///
/// # Django Equivalent
/// ```python
/// # Django: django/apps/registry.py
/// class Apps:
///     def __init__(self):
///         self.all_models = defaultdict(dict)  # {app_label: {model_name: model_class}}
///
///     def register_model(self, app_label, model):
///         model_name = model._meta.model_name
///         self.all_models[app_label][model_name] = model
///
///     def get_models(self, include_auto_created=False, include_swapped=False):
///         result = []
///         for app_config in self.app_configs.values():
///             result.extend(app_config.get_models(include_auto_created, include_swapped))
///         return result
/// ```
#[derive(Debug, Clone)]
pub struct ModelRegistry {
	/// Models: (app_label, model_name) -> ModelMetadata
	models: Arc<RwLock<HashMap<(String, String), ModelMetadata>>>,
}

impl ModelRegistry {
	/// Creates a new instance.
	pub fn new() -> Self {
		Self {
			models: Arc::new(RwLock::new(HashMap::new())),
		}
	}

	/// Register a model in the registry
	///
	/// # Django Reference
	/// From: django/apps/registry.py:215-240
	/// ```python
	/// def register_model(self, app_label, model):
	///     model_name = model._meta.model_name
	///     app_models = self.all_models[app_label]
	///     if model_name in app_models:
	///         # Handle conflicts...
	///     app_models[model_name] = model
	/// ```
	pub fn register_model(&self, metadata: ModelMetadata) {
		let key = (metadata.app_label.clone(), metadata.model_name.clone());
		if let Ok(mut models) = self.models.write() {
			models.insert(key, metadata);
		}
	}

	/// Get all registered models
	///
	/// Returns a freshly-cloned `Vec<ModelMetadata>`. For hot paths that
	/// only need to look up a single model, prefer
	/// [`Self::find_model_qualified`] (when the target app is known) or
	/// [`Self::find_model_by_name`] (when only the model name is known)
	/// to avoid materializing the entire registry on each call.
	///
	/// # Django Reference
	/// From: django/apps/registry.py:169-186
	/// ```python
	/// def get_models(self, include_auto_created=False, include_swapped=False):
	///     result = []
	///     for app_config in self.app_configs.values():
	///         result.extend(app_config.get_models(include_auto_created, include_swapped))
	///     return result
	/// ```
	pub fn get_models(&self) -> Vec<ModelMetadata> {
		if let Ok(models) = self.models.read() {
			models.values().cloned().collect()
		} else {
			Vec::new()
		}
	}

	/// Get a specific model by app_label and model_name
	///
	/// # Django Reference
	/// From: django/apps/registry.py:188-213
	/// ```python
	/// def get_model(self, app_label, model_name=None, require_ready=True):
	///     if model_name is None:
	///         app_label, model_name = app_label.split(".")
	///     app_config = self.get_app_config(app_label)
	///     return app_config.get_model(model_name, require_ready=require_ready)
	/// ```
	pub fn get_model(&self, app_label: &str, model_name: &str) -> Option<ModelMetadata> {
		if let Ok(models) = self.models.read() {
			models
				.get(&(app_label.to_string(), model_name.to_string()))
				.cloned()
		} else {
			None
		}
	}

	/// Find a model by `(app_label, model_name)` without materializing the
	/// entire registry.
	///
	/// The cost is an O(1) index lookup plus a single clone of the matched
	/// [`ModelMetadata`] (whose size depends on its `fields` vector). This
	/// is the preferred path for hot code (e.g. migration generation, FK
	/// column type resolution) where [`Self::get_models`] would otherwise
	/// clone every registered model on every call.
	///
	/// Semantically equivalent to [`Self::get_model`]; named to make the
	/// "qualified lookup" intent explicit at call sites. See issue #4436.
	pub fn find_model_qualified(&self, app_label: &str, model_name: &str) -> Option<ModelMetadata> {
		self.get_model(app_label, model_name)
	}

	/// Find a model by `model_name` alone, without an app label.
	///
	/// Scans the registry values under the read lock but clones only the
	/// matched entry (not the entire registry), so it avoids the
	/// `Vec<ModelMetadata>` materialization in [`Self::get_models`].
	///
	/// # Ambiguity
	///
	/// If two or more apps have registered a model with the same
	/// `model_name`, this function returns `None` and emits a
	/// `tracing::warn!` (one log line per call — there is no
	/// deduplication, so callers on a hot path should switch to
	/// [`Self::find_model_qualified`]). Callers that need a specific
	/// cross-app FK target must use [`Self::find_model_qualified`]
	/// instead. This conservative behavior prevents the silent
	/// wrong-target resolution flagged on PR #4434 (Copilot review
	/// thread HYL).
	///
	/// See issue #4436.
	pub fn find_model_by_name(&self, model_name: &str) -> Option<ModelMetadata> {
		let models = self.models.read().ok()?;
		let mut matches = models.values().filter(|m| m.model_name == model_name);
		let first = matches.next()?.clone();
		if matches.next().is_some() {
			tracing::warn!(
				model_name,
				"ModelRegistry::find_model_by_name: ambiguous model name registered \
				 under multiple app labels; returning None. Use \
				 ModelRegistry::find_model_qualified(app, name) to disambiguate.",
			);
			return None;
		}
		Some(first)
	}

	/// Count how many registered models have `model_name`, irrespective
	/// of app label.
	///
	/// Used by [`crate::migrations::operations`] FK column-type
	/// resolution to distinguish "model name is genuinely missing" from
	/// "model name is registered under more than one app" when a
	/// by-name lookup returns `None`. The two cases need different
	/// diagnostics: ambiguity is a user error worth a `tracing::warn!`,
	/// while a missing name is normal during partial registry
	/// population at startup.
	///
	/// See issue #4436.
	pub fn count_models_by_name(&self, model_name: &str) -> usize {
		if let Ok(models) = self.models.read() {
			models
				.values()
				.filter(|m| m.model_name == model_name)
				.count()
		} else {
			0
		}
	}

	/// Get all models for a specific app
	pub fn get_app_models(&self, app_label: &str) -> Vec<ModelMetadata> {
		if let Ok(models) = self.models.read() {
			models
				.iter()
				.filter(|((app, _), _)| app == app_label)
				.map(|(_, meta)| meta.clone())
				.collect()
		} else {
			Vec::new()
		}
	}

	/// Remove a model from the registry
	pub fn remove_model(&self, app_label: &str, model_name: &str) -> bool {
		if let Ok(mut models) = self.models.write() {
			models
				.remove(&(app_label.to_string(), model_name.to_string()))
				.is_some()
		} else {
			false
		}
	}

	/// Clear all registered models
	pub fn clear(&self) {
		if let Ok(mut models) = self.models.write() {
			models.clear();
		}
	}

	/// Get the count of registered models
	pub fn count(&self) -> usize {
		if let Ok(models) = self.models.read() {
			models.len()
		} else {
			0
		}
	}
}

impl Default for ModelRegistry {
	fn default() -> Self {
		Self::new()
	}
}

/// Global model registry instance
///
/// This is the primary way to access the model registry from anywhere in the application.
pub fn global_registry() -> &'static ModelRegistry {
	use once_cell::sync::Lazy;
	static REGISTRY: Lazy<ModelRegistry> = Lazy::new(ModelRegistry::new);
	&REGISTRY
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::migrations::FieldType;
	use rstest::rstest;

	#[test]
	fn test_model_registry_new() {
		let registry = ModelRegistry::new();
		assert_eq!(registry.count(), 0);
	}

	#[test]
	fn test_register_model() {
		let registry = ModelRegistry::new();
		let metadata = ModelMetadata::new("blog", "Post", "blog_post");
		registry.register_model(metadata);
		assert_eq!(registry.count(), 1);
	}

	#[test]
	fn test_get_model() {
		let registry = ModelRegistry::new();
		let metadata = ModelMetadata::new("auth", "User", "auth_user");
		registry.register_model(metadata);

		let retrieved = registry.get_model("auth", "User");
		assert!(retrieved.is_some());
		assert_eq!(retrieved.unwrap().table_name, "auth_user");
	}

	#[test]
	fn test_get_models() {
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("blog", "Post", "blog_post"));

		let models = registry.get_models();
		assert_eq!(models.len(), 2);
	}

	#[test]
	fn test_find_model_qualified_hit() {
		// Arrange
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("blog", "Post", "blog_post"));

		// Act
		let hit = registry.find_model_qualified("auth", "User");

		// Assert
		assert!(hit.is_some());
		let model = hit.unwrap();
		assert_eq!(model.app_label, "auth");
		assert_eq!(model.model_name, "User");
		assert_eq!(model.table_name, "auth_user");
	}

	#[test]
	fn test_find_model_qualified_miss_wrong_app() {
		// Arrange
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));

		// Act / Assert: same model name registered under a different app
		// must not be returned.
		assert!(registry.find_model_qualified("billing", "User").is_none());
	}

	#[test]
	fn test_find_model_by_name_unique() {
		// Arrange
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("blog", "Post", "blog_post"));

		// Act
		let hit = registry.find_model_by_name("Post");

		// Assert
		assert!(hit.is_some());
		assert_eq!(hit.unwrap().app_label, "blog");
	}

	#[test]
	fn test_find_model_by_name_missing() {
		// Arrange
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));

		// Act / Assert
		assert!(registry.find_model_by_name("NoSuchModel").is_none());
	}

	#[test]
	fn test_find_model_by_name_ambiguous_returns_none() {
		// Arrange: same model name registered under two different apps.
		// The conservative behavior is to refuse the unqualified lookup
		// rather than silently pick one (issue #4436, PR #4434 thread HYL).
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("billing", "User", "billing_user"));

		// Act
		let hit = registry.find_model_by_name("User");

		// Assert
		assert!(hit.is_none());
	}

	#[test]
	fn test_get_app_models() {
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("auth", "Group", "auth_group"));
		registry.register_model(ModelMetadata::new("blog", "Post", "blog_post"));

		let auth_models = registry.get_app_models("auth");
		assert_eq!(auth_models.len(), 2);

		let blog_models = registry.get_app_models("blog");
		assert_eq!(blog_models.len(), 1);
	}

	#[test]
	fn test_remove_model() {
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));

		assert!(registry.remove_model("auth", "User"));
		assert_eq!(registry.count(), 0);
	}

	#[test]
	fn test_migrations_registry_clear() {
		let registry = ModelRegistry::new();
		registry.register_model(ModelMetadata::new("auth", "User", "auth_user"));
		registry.register_model(ModelMetadata::new("blog", "Post", "blog_post"));

		registry.clear();
		assert_eq!(registry.count(), 0);
	}

	#[test]
	fn test_model_metadata_to_model_state() {
		let mut metadata = ModelMetadata::new("blog", "Post", "blog_post");

		let mut title_field = FieldMetadata::new(FieldType::Custom("CharField".to_string()));
		title_field
			.params
			.insert("max_length".to_string(), "200".to_string());
		metadata.add_field("title".to_string(), title_field);

		let model_state = metadata.to_model_state();
		assert_eq!(model_state.name, "Post");
		assert_eq!(model_state.fields.len(), 1);
		assert!(model_state.fields.contains_key("title"));
	}

	#[test]
	fn test_field_metadata_builder() {
		let field = FieldMetadata::new(FieldType::Custom("CharField".to_string()))
			.with_param("max_length", "100")
			.with_param("null", "False");

		assert_eq!(field.field_type, FieldType::Custom("CharField".to_string()));
		assert_eq!(field.params.get("max_length").unwrap(), "100");
		assert_eq!(field.params.get("null").unwrap(), "False");
	}

	#[rstest]
	#[case("true", true)]
	#[case("false", false)]
	fn test_to_model_state_overrides_nullable_from_params(
		#[case] null_param: &str,
		#[case] expected_nullable: bool,
	) {
		// Arrange
		let mut metadata = ModelMetadata::new("blog", "Post", "blog_post");
		let field = FieldMetadata::new(FieldType::Custom("CharField".to_string()))
			.with_param("max_length", "200")
			.with_param("null", null_param);
		metadata.add_field("description".to_string(), field);

		// Act
		let model_state = metadata.to_model_state();

		// Assert
		let field_state = model_state.fields.get("description").unwrap();
		assert_eq!(field_state.nullable, expected_nullable);
	}

	#[rstest]
	fn to_model_state_nullable_false_for_primary_key_matches_macro_contract() {
		// Arrange — regression for issue #4052.
		//
		// The `#[model]` macro must emit `null = "false"` for primary key
		// fields regardless of whether the Rust type is `Option<T>`. The
		// `Option<T>` wrapper for PKs is a Rust-side convention to allow
		// `id = None` before the DB assigns the auto-increment value, not
		// a DB-level nullability statement. PK columns are always NOT NULL
		// at the DB level.
		//
		// This test codifies the contract that `to_model_state` consumes
		// from the macro: with the fixed macro params, the resulting
		// `FieldState.nullable` for an `Option<i64>` PK must be `false`,
		// matching the migration-replay path's
		// `column_def_to_field_state(...).nullable = !col.not_null = false`.
		//
		// Pre-fix, the macro emitted `null = "true"` for any Option<T>
		// field including PKs, producing `FieldState.nullable = true` and
		// surfacing as a spurious `AlterColumn` for the unchanged PK in
		// offline `makemigrations` runs.
		let mut metadata = ModelMetadata::new("clusters", "Cluster", "clusters");
		// Mirror the fixed macro params for `id: Option<i64>` with
		// `#[field(primary_key = true)]`: `null = "false"` (forced by the
		// fix), `not_null = "true"`, `primary_key = "true"`,
		// `auto_increment = "true"`.
		let id_field = FieldMetadata::new(FieldType::BigInteger)
			.with_param("primary_key", "true")
			.with_param("auto_increment", "true")
			.with_param("not_null", "true")
			.with_param("null", "false");
		metadata.add_field("id".to_string(), id_field);

		// Act
		let model_state = metadata.to_model_state();

		// Assert — nullable=false on the FieldState side, regardless of
		// the underlying Rust Option<T> wrapping.
		let id_state = model_state
			.fields
			.get("id")
			.expect("id field present in to_model_state output");
		assert!(
			!id_state.nullable,
			"PK FieldState.nullable must be false even when the Rust type is \
			 Option<i64>. Did the #[model] macro regress to emitting \
			 null=\"true\" for Option<T> PKs? params={:?}",
			id_state.params
		);
		assert_eq!(
			id_state.params.get("null").map(String::as_str),
			Some("false"),
			"PK params[\"null\"] must be \"false\" (fixed macro contract). \
			 Got params={:?}",
			id_state.params
		);
	}
}