reinhardt-rest 0.1.2

REST API framework aggregator for Reinhardt
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
//! NestedSerializer - Django REST Framework inspired nested serialization
//!
//! This module provides serializers for handling nested relationships between models,
//! enabling complex object graphs to be serialized and deserialized.
//!
//! # Relationship Loading Strategy
//!
//! Following Django REST Framework's design philosophy, `NestedSerializer` works with
//! data that is **already loaded** by the ORM layer. This separation of concerns means:
//!
//! - **ORM Layer (reinhardt-orm)**: Responsible for loading related data using
//!   `LoadingStrategy` (Lazy, Joined, Selectin, etc.)
//! - **Serializer Layer**: Responsible for serializing the already-loaded data to JSON
//!
//! ## Usage Pattern
//!
//! ```rust,no_run,ignore
//! // 1. Load data with relationships using ORM
//! let posts = Post::objects()
//!     .select_related("author")  // Load author relationship
//!     .all()
//!     .await?;
//!
//! // 2. Serialize with NestedSerializer
//! let serializer = NestedSerializer::<Post, Author>::new("author").depth(1);
//! for post in posts {
//!     let json = serializer.serialize(&post)?;
//!     // JSON includes author data if it was loaded
//! }
//! ```
//!
//! This design avoids the N+1 query problem and gives developers explicit control
//! over when and how relationships are loaded.
//!
//! ## Limitations of the synchronous trait API
//!
//! The [`Serializer`] trait is synchronous, so the [`Serializer::serialize`]
//! and [`Serializer::deserialize`] implementations on [`NestedSerializer`] and
//! [`WritableNestedSerializer`] cannot reach the database:
//!
//! - `serialize` emits whatever was preloaded and never lazy-loads. A null
//!   `relationship_field` stays null in the output.
//! - `WritableNestedSerializer::deserialize` validates structure and
//!   permissions but returns only the parent model. To act on nested writes,
//!   pair it with [`WritableNestedSerializer::extract_nested_data`] and
//!   dispatch the result to your ORM inside a transaction.
//! - `depth` controls how deeply the arena re-walks already-loaded data; it
//!   does not trigger additional loads.

use super::{SerializationArena, Serializer, SerializerError};
use reinhardt_db::orm::Model;
use serde_json::Value;
use std::marker::PhantomData;

// Module-private helper used by both `NestedSerializer` and
// `WritableNestedSerializer` to emit the parent model's JSON. The arena path
// honors prefetched relationship data already present in the serialized form;
// it never triggers ORM lazy loading.
fn serialize_via_arena_or_plain<M: Model>(
	input: &M,
	depth: usize,
	use_arena: bool,
) -> Result<String, SerializerError> {
	if use_arena {
		let arena = SerializationArena::new();
		let serialized = arena.serialize_model(input, depth);
		let json_value = arena.to_json(serialized);
		serde_json::to_string(&json_value).map_err(|e| SerializerError::Other {
			message: format!("Serialization error: {}", e),
		})
	} else {
		serde_json::to_string(input).map_err(|e| SerializerError::Other {
			message: format!("Serialization error: {}", e),
		})
	}
}

/// NestedSerializer - Serialize related models inline
///
/// Handles one-to-one and many-to-one relationships by embedding the related
/// model's data directly in the serialized output.
///
/// # Examples
///
/// ```
/// # use reinhardt_rest::serializers::NestedSerializer;
/// # use reinhardt_db::orm::Model;
/// # use serde::{Serialize, Deserialize};
/// #
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct Post {
/// #     id: Option<i64>,
/// #     title: String,
/// #     author_id: i64,
/// # }
/// #
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct Author {
/// #     id: Option<i64>,
/// #     name: String,
/// # }
/// #
/// # impl Model for Post {
/// #     type PrimaryKey = i64;
/// #     type Fields = PostFields;
/// #     fn table_name() -> &'static str { "posts" }
/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// #     fn new_fields() -> Self::Fields { PostFields }
/// # }
/// # #[derive(Clone)]
/// # struct PostFields;
/// # impl reinhardt_db::orm::FieldSelector for PostFields {
/// #     fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// #
/// # impl Model for Author {
/// #     type PrimaryKey = i64;
/// #     type Fields = AuthorFields;
/// #     fn table_name() -> &'static str { "authors" }
/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// #     fn new_fields() -> Self::Fields { AuthorFields }
/// # }
/// # #[derive(Clone)]
/// # struct AuthorFields;
/// # impl reinhardt_db::orm::FieldSelector for AuthorFields {
/// #     fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// #
/// # fn example() {
/// // Serialize a post with its author nested
/// let serializer = NestedSerializer::<Post, Author>::new("author");
/// // Verify the serializer is created successfully
/// let _: NestedSerializer<Post, Author> = serializer;
/// # }
/// ```
pub struct NestedSerializer<M: Model, R: Model> {
	relationship_field: String,
	depth: usize,
	use_arena: bool,
	_phantom: PhantomData<(M, R)>,
}

impl<M: Model, R: Model> NestedSerializer<M, R> {
	/// Create a new NestedSerializer
	///
	/// # Arguments
	///
	/// * `relationship_field` - The field name that contains the related model
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_rest::serializers::NestedSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// #
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Post { id: Option<i64>, title: String }
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Author { id: Option<i64>, name: String }
	/// #
	/// # impl Model for Post {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = PostFields;
	/// #     fn table_name() -> &'static str { "posts" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { PostFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct PostFields;
	/// # impl reinhardt_db::orm::FieldSelector for PostFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// #
	/// # impl Model for Author {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = AuthorFields;
	/// #     fn table_name() -> &'static str { "authors" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { AuthorFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct AuthorFields;
	/// # impl reinhardt_db::orm::FieldSelector for AuthorFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// let serializer = NestedSerializer::<Post, Author>::new("author");
	/// // Verify the serializer is created successfully
	/// let _: NestedSerializer<Post, Author> = serializer;
	/// ```
	pub fn new(relationship_field: impl Into<String>) -> Self {
		Self {
			relationship_field: relationship_field.into(),
			depth: 1,
			use_arena: true,
			_phantom: PhantomData,
		}
	}

	/// Set the nesting depth (default: 1)
	///
	/// Controls how many levels of relationships to serialize.
	/// depth=0 means no nesting (like ModelSerializer),
	/// depth=1 means serialize immediate relationships,
	/// depth=2+ means serialize nested relationships of relationships.
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_rest::serializers::NestedSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// #
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Post { id: Option<i64>, title: String }
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Author { id: Option<i64>, name: String }
	/// #
	/// # impl Model for Post {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = PostFields;
	/// #     fn table_name() -> &'static str { "posts" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { PostFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct PostFields;
	/// # impl reinhardt_db::orm::FieldSelector for PostFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// #
	/// # impl Model for Author {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = AuthorFields;
	/// #     fn table_name() -> &'static str { "authors" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { AuthorFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct AuthorFields;
	/// # impl reinhardt_db::orm::FieldSelector for AuthorFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// let serializer = NestedSerializer::<Post, Author>::new("author")
	///     .depth(2); // Serialize author and author's relationships
	/// // Verify depth configuration
	/// let _: NestedSerializer<Post, Author> = serializer;
	/// ```
	pub fn depth(mut self, depth: usize) -> Self {
		self.depth = depth;
		self
	}

	/// Disable arena allocation (use traditional heap allocation instead)
	///
	/// This is provided for backward compatibility or when arena allocation
	/// is not desired. By default, arena allocation is enabled.
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_rest::serializers::NestedSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// #
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Post { id: Option<i64>, title: String }
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Author { id: Option<i64>, name: String }
	/// #
	/// # impl Model for Post {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = PostFields;
	/// #     fn table_name() -> &'static str { "posts" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { PostFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct PostFields;
	/// # impl reinhardt_db::orm::FieldSelector for PostFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// #
	/// # impl Model for Author {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = AuthorFields;
	/// #     fn table_name() -> &'static str { "authors" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { AuthorFields }
	/// # }
	/// # #[derive(Clone)]
	/// # struct AuthorFields;
	/// # impl reinhardt_db::orm::FieldSelector for AuthorFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// let serializer = NestedSerializer::<Post, Author>::new("author")
	///     .without_arena(); // Disable arena allocation
	/// // Verify arena allocation is disabled
	/// let _: NestedSerializer<Post, Author> = serializer;
	/// ```
	pub fn without_arena(mut self) -> Self {
		self.use_arena = false;
		self
	}
}

impl<M: Model, R: Model> Serializer for NestedSerializer<M, R> {
	type Input = M;
	type Output = String;

	/// Serialize the parent model honoring already-loaded relationships.
	///
	/// This method does **not** trigger ORM lazy loading. If the
	/// `relationship_field` is null in the parent JSON, it stays null in the
	/// output — no additional query is issued. To preload relationships, use
	/// `QuerySet::select_related` / `prefetch_related` in the view layer
	/// before calling [`Self::serialize`].
	fn serialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError> {
		if self.use_arena {
			serialize_via_arena_or_plain(input, self.depth, true)
		} else {
			// `serialize_without_arena` keeps a depth > 0 sentinel that
			// inspects the relationship field for prefetched data; the bare
			// arena path does not need that branch.
			self.serialize_without_arena(input)
		}
	}

	fn deserialize(&self, output: &Self::Output) -> Result<Self::Input, SerializerError> {
		serde_json::from_str(output).map_err(|e| SerializerError::Other {
			message: format!("Deserialization error: {}", e),
		})
	}
}

impl<M: Model, R: Model> NestedSerializer<M, R> {
	/// Serialize without using arena allocation (traditional approach)
	fn serialize_without_arena(&self, input: &M) -> Result<String, SerializerError> {
		// Serialize parent model to JSON
		let mut parent_value = serde_json::to_value(input).map_err(|e| SerializerError::Other {
			message: format!("Serialization error: {}", e),
		})?;

		// If depth > 0, check if relationship data is already loaded in the parent JSON
		// This follows Django REST Framework's approach where related data is loaded
		// by the ORM layer (e.g., using select_related/prefetch_related) before serialization
		if self.depth > 0
			&& let Some(obj) = parent_value.as_object_mut()
		{
			// Check if the relationship field already has data
			if let Some(related_data) = obj.get(&self.relationship_field) {
				// If the data is not null, it means the relationship was already loaded
				// by the ORM (e.g., via Joined or Selectin loading strategy)
				if !related_data.is_null() {
					// The relationship data is already present in the serialized JSON
					// This works because reinhardt-orm's Model trait implementations
					// include relationship fields in their Serialize implementation
					// when those relationships are loaded
				}
			}
		}

		// Convert the value back to string
		serde_json::to_string(&parent_value).map_err(|e| SerializerError::Other {
			message: format!("Serialization error: {}", e),
		})
	}
}

/// ListSerializer - Serialize collections of models
///
/// Handles serializing multiple instances efficiently, useful for
/// many-to-many and reverse foreign key relationships.
///
/// # Examples
///
/// ```
/// # use reinhardt_rest::serializers::ListSerializer;
/// # use reinhardt_db::orm::Model;
/// # use serde::{Serialize, Deserialize};
/// #
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct User {
/// #     id: Option<i64>,
/// #     username: String,
/// # }
/// #
/// # impl Model for User {
/// #     type PrimaryKey = i64;
/// #     type Fields = UserFields;
/// #     fn table_name() -> &'static str { "users" }
/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// #     fn new_fields() -> Self::Fields { UserFields }
/// # }
/// # #[derive(Clone)]
/// # struct UserFields;
/// # impl reinhardt_db::orm::FieldSelector for UserFields {
/// #     fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// let serializer = ListSerializer::<User>::new();
/// // Verify the serializer is created successfully
/// let _: ListSerializer<User> = serializer;
/// ```
pub struct ListSerializer<M: Model> {
	_phantom: PhantomData<M>,
}

impl<M: Model> ListSerializer<M> {
	/// Create a new ListSerializer
	pub fn new() -> Self {
		Self {
			_phantom: PhantomData,
		}
	}
}

impl<M: Model> Default for ListSerializer<M> {
	fn default() -> Self {
		Self::new()
	}
}

impl<M: Model> Serializer for ListSerializer<M> {
	type Input = Vec<M>;
	type Output = String;

	fn serialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError> {
		serde_json::to_string(input).map_err(|e| SerializerError::Other {
			message: format!("Serialization error: {}", e),
		})
	}

	fn deserialize(&self, output: &Self::Output) -> Result<Self::Input, SerializerError> {
		serde_json::from_str(output).map_err(|e| SerializerError::Other {
			message: format!("Deserialization error: {}", e),
		})
	}
}

/// WritableNestedSerializer - Serialize and create/update nested models
///
/// Extends NestedSerializer to support write operations on nested relationships.
/// This allows creating or updating related models when the parent is saved.
///
/// # Design Philosophy
///
/// This serializer follows the **separation of concerns** principle:
/// - **Validation**: The serializer validates JSON structure and permissions
/// - **Data Extraction**: Provides helper methods to extract nested data
/// - **Database Operations**: Caller handles ORM operations and transactions
///
/// This design gives you full control over transaction management and error handling
/// while the serializer ensures data validity.
///
/// # Permission Control
///
/// - `allow_create(bool)`: Allow creating new related instances (default: false)
/// - `allow_update(bool)`: Allow updating existing related instances (default: false)
///
/// Without these permissions, deserialization will fail if nested data contains
/// create/update operations.
///
/// # Usage Patterns
///
/// ## Basic Usage with Manual ORM Integration
///
/// ```rust,ignore
/// # #[tokio::main]
/// # async fn main() {
/// use reinhardt_rest::serializers::WritableNestedSerializer;
/// use reinhardt_db::orm::{Model, Transaction};
///
/// // Define serializer with permissions
/// let serializer = WritableNestedSerializer::<Post, Author>::new("author")
///     .allow_create(true)
///     .allow_update(true);
///
/// // JSON with nested author
/// let json = r#"{
///     "title": "My Post",
///     "author": {
///         "id": null,
///         "name": "Alice"
///     }
/// }"#;
///
/// // Validate and deserialize
/// let post: Post = serializer.deserialize(&json.to_string())?;
///
/// // Extract nested data for manual processing
/// if let Some(author_data) = serializer.extract_nested_data(json)? {
///     // Create author within transaction
///     let mut tx = Transaction::new();
///     tx.begin()?;
///
///     let author: Author = serde_json::from_value(author_data)?;
///     let saved_author = Author::objects().create(&author).await?;
///
///     // Set foreign key and save parent
///     post.author_id = saved_author.id;
///     let saved_post = Post::objects().create(&post).await?;
///
///     tx.commit()?;
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # }
/// ```
///
/// ## Advanced: Handling Both Create and Update
///
/// ```rust,ignore
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use serde_json::json;
/// # use reinhardt_db::orm::{Model, Transaction};
/// # use reinhardt_rest::serializers::WritableNestedSerializer;
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Author { id: Option<i64>, name: String }
/// # impl Model for Author {
/// #     type PrimaryKey = i64;
/// #     fn table_name() -> &'static str { "authors" }
/// #     fn primary_key(&self) -> Option<&i64> { self.id.as_ref() }
/// #     fn set_primary_key(&mut self, value: i64) { self.id = Some(value); }
/// # }
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Post { id: i64, title: String, author_id: i64 }
/// # impl Model for Post {
/// #     type PrimaryKey = i64;
/// #     fn table_name() -> &'static str { "posts" }
/// #     fn primary_key(&self) -> Option<&i64> { Some(&self.id) }
/// #     fn set_primary_key(&mut self, value: i64) { self.id = value; }
/// # }
/// # let serializer = WritableNestedSerializer::<Post, Author>::new();
/// # let json = json!({});
/// if let Some(author_data) = serializer.extract_nested_data(json)? {
///     let mut tx = Transaction::new();
///     tx.begin()?;
///
///     let author: Author = serde_json::from_value(author_data)?;
///     let saved_author = if WritableNestedSerializer::<Post, Author>::is_create_operation(&author_data) {
///         // Create new author
///         Author::objects().create(&author).await?
///     } else {
///         // Update existing author
///         Author::objects().update(&author).await?
///     };
///
///     post.author_id = saved_author.id;
///     Post::objects().create(&post).await?;
///
///     tx.commit()?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// The serializer returns `SerializerError` in these cases:
/// - JSON parsing fails
/// - Nested data violates permissions (create/update not allowed)
/// - Invalid nested data structure
///
/// Database errors are handled by the caller during ORM operations.
///
/// # Examples
///
/// ```
/// # use reinhardt_rest::serializers::WritableNestedSerializer;
/// # use reinhardt_db::orm::Model;
/// # use serde::{Serialize, Deserialize};
/// #
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct Post { id: Option<i64>, title: String }
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct Comment { id: Option<i64>, text: String }
/// #
/// # impl Model for Post {
/// #     type PrimaryKey = i64;
/// #     type Fields = PostFields;
/// #     fn table_name() -> &'static str { "posts" }
/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// #     fn new_fields() -> Self::Fields { PostFields }
/// # }
/// # #[derive(Clone)]
/// # struct PostFields;
/// # impl reinhardt_db::orm::FieldSelector for PostFields {
/// #     fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// #
/// # impl Model for Comment {
/// #     type PrimaryKey = i64;
/// #     type Fields = CommentFields;
/// #     fn table_name() -> &'static str { "comments" }
/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// #     fn new_fields() -> Self::Fields { CommentFields }
/// # }
/// # #[derive(Clone)]
/// # struct CommentFields;
/// # impl reinhardt_db::orm::FieldSelector for CommentFields {
/// #     fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// #
/// # fn example() {
/// // Create a post and its comments in one operation
/// let serializer = WritableNestedSerializer::<Post, Comment>::new("comments")
///     .allow_create(true);
/// // Verify the serializer is created with create permission
/// let _: WritableNestedSerializer<Post, Comment> = serializer;
/// # }
/// ```
pub struct WritableNestedSerializer<M: Model, R: Model> {
	relationship_field: String,
	allow_create: bool,
	allow_update: bool,
	_phantom: PhantomData<(M, R)>,
}

impl<M: Model, R: Model> WritableNestedSerializer<M, R> {
	/// Create a new WritableNestedSerializer
	pub fn new(relationship_field: impl Into<String>) -> Self {
		Self {
			relationship_field: relationship_field.into(),
			allow_create: false,
			allow_update: false,
			_phantom: PhantomData,
		}
	}

	/// Allow creating new related instances (default: false)
	pub fn allow_create(mut self, allow: bool) -> Self {
		self.allow_create = allow;
		self
	}

	/// Allow updating existing related instances (default: false)
	pub fn allow_update(mut self, allow: bool) -> Self {
		self.allow_update = allow;
		self
	}

	/// Extract nested data from JSON for manual processing
	///
	/// Returns the nested data as a serde_json::Value for the caller to process.
	/// This allows the caller to handle database operations with full control.
	///
	/// # Examples
	///
	/// ```ignore
	/// let serializer = WritableNestedSerializer::<Post, Author>::new("author");
	/// let json = r#"{"id": 1, "title": "Post", "author": {"id": 2, "name": "Alice"}}"#;
	///
	/// if let Some(nested_data) = serializer.extract_nested_data(json)? {
	///     // Verify nested data extraction succeeds
	///     let author: Author = serde_json::from_value(nested_data)?;
	/// }
	/// ```
	pub fn extract_nested_data(&self, json: &str) -> Result<Option<Value>, SerializerError> {
		let value: Value = serde_json::from_str(json).map_err(|e| SerializerError::Other {
			message: format!("JSON parsing error: {}", e),
		})?;

		if let Value::Object(ref map) = value
			&& let Some(nested_value) = map.get(&self.relationship_field)
			&& !nested_value.is_null()
		{
			return Ok(Some(nested_value.clone()));
		}

		Ok(None)
	}

	/// Check if nested data represents a create operation (no primary key or null primary key)
	///
	/// # Examples
	///
	/// ```ignore
	/// let create_data = serde_json::json!({"id": null, "name": "New Author"});
	/// // Verify create operation detection
	/// assert!(WritableNestedSerializer::<Post, Author>::is_create_operation(&create_data));
	///
	/// let update_data = serde_json::json!({"id": 42, "name": "Existing Author"});
	/// // Verify update operation detection
	/// assert!(!WritableNestedSerializer::<Post, Author>::is_create_operation(&update_data));
	/// ```
	pub fn is_create_operation(nested_value: &Value) -> bool {
		if let Some(pk) = nested_value.get(M::primary_key_field()) {
			pk.is_null()
		} else {
			true // No primary key field means create
		}
	}
}

impl<M: Model, R: Model> Serializer for WritableNestedSerializer<M, R> {
	type Input = M;
	type Output = String;

	/// Serialize the parent model honoring already-loaded relationships.
	///
	/// Mirrors [`NestedSerializer::serialize`] (depth `1`, arena enabled): it
	/// emits whatever relationship data was preloaded by the ORM and never
	/// triggers lazy loading. For relationships you need to materialize at
	/// response time, preload them via `select_related` /
	/// `prefetch_related` in the view layer.
	fn serialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError> {
		serialize_via_arena_or_plain(input, 1, true)
	}

	/// Validate the parent JSON structure and nested-write permissions.
	///
	/// Returns the parent model only. Nested data is **not** materialized
	/// into the returned `M` — call [`Self::extract_nested_data`] on the
	/// same JSON to obtain the related-object payload, then perform the
	/// create / update via the ORM in your view code.
	///
	/// Permission flags are enforced here: nested writes that violate
	/// `allow_create` or `allow_update` cause this method to return
	/// `SerializerError::Other`.
	fn deserialize(&self, output: &Self::Output) -> Result<Self::Input, SerializerError> {
		// Parse JSON to validate structure
		let value: Value = serde_json::from_str(output).map_err(|e| SerializerError::Other {
			message: format!("JSON parsing error: {}", e),
		})?;

		// Check for nested data at relationship_field
		if let Value::Object(ref map) = value
			&& let Some(nested_value) = map.get(&self.relationship_field)
		{
			// Validate permissions
			if nested_value.is_object() {
				// Single related object
				if let Some(pk) = nested_value.get(M::primary_key_field()) {
					if pk.is_null() && !self.allow_create {
						return Err(SerializerError::Other {
							message: "Creating nested instances is not allowed".to_string(),
						});
					} else if !pk.is_null() && !self.allow_update {
						return Err(SerializerError::Other {
							message: "Updating nested instances is not allowed".to_string(),
						});
					}
				}
			} else if nested_value.is_array() {
				// Multiple related objects
				for item in nested_value.as_array().unwrap() {
					if let Some(pk) = item.get(M::primary_key_field()) {
						if pk.is_null() && !self.allow_create {
							return Err(SerializerError::Other {
								message: "Creating nested instances is not allowed".to_string(),
							});
						} else if !pk.is_null() && !self.allow_update {
							return Err(SerializerError::Other {
								message: "Updating nested instances is not allowed".to_string(),
							});
						}
					}
				}
			}

			// Nested data validation passed
			// The actual database operations (create/update) are handled by the caller
			// using ORM methods like QuerySet::create() or Model::save()
			//
			// This design follows the separation of concerns principle:
			// - Serializer: Validates structure and permissions
			// - ORM Layer: Performs database operations
			// - Transaction: Ensures atomicity
			//
			// Example usage pattern:
			// ```
			// let serializer = WritableNestedSerializer::new("author").allow_create(true);
			// let post: Post = serializer.deserialize(&json)?;
			//
			// // Caller handles database operations within transaction:
			// let mut tx = Transaction::new();
			// tx.begin()?;
			// let author = Author::objects().create(&post.author).await?;
			// post.author_id = author.id;
			// let saved_post = Post::objects().create(&post).await?;
			// tx.commit()?;
			// ```
		}

		// This method intentionally deserializes only the parent model.
		// Following Django REST Framework's separation of concerns:
		// - Serializer: Validates JSON structure and permissions
		// - ORM Layer: Handles database operations (caller's responsibility)
		// - Use extract_nested_data() and is_create_operation() for nested processing
		serde_json::from_str(output).map_err(|e| SerializerError::Other {
			message: format!("Deserialization error: {}", e),
		})
	}
}