autumn-web 0.3.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Mutation hook types for repository lifecycle callbacks.
//!
//! This module provides the types and trait that power before/after mutation
//! hooks on generated repositories (create, update, delete).
//!
//! # Opting in
//!
//! By default, repositories generated by `#[repository(Model)]` perform
//! plain CRUD with no hook overhead. To enable hooks, pass a hooks type:
//!
//! ```rust,ignore
//! #[derive(Clone, Default)]
//! struct ArticleHooks;
//!
//! impl MutationHooks for ArticleHooks {
//!     type Model = Article;
//!     type NewModel = NewArticle;
//!     type UpdateModel = UpdateArticle;
//!
//!     // override only the callbacks you need …
//! }
//!
//! #[repository(Article, hooks = ArticleHooks)]
//! pub trait ArticleRepository {}
//! ```
//!
//! The hooks type **must** implement [`Default`] and [`Clone`] (the
//! generated extractor constructs it via `Default::default()` and the
//! repository struct derives `Clone`).
//!
//! # Lifecycle
//!
//! Every mutating CRUD operation follows the same lifecycle:
//!
//! 1. **`before_*`** -- called before the mutation with a mutable
//!    reference to the [`MutationContext`] and the input/model. The hook
//!    may validate, enrich, or reject (by returning `Err`).
//! 2. **persist** -- the actual `INSERT`, `UPDATE`, or `DELETE` runs.
//!
//! # Error semantics
//!
//! - `before_*` errors prevent the mutation entirely.
//!
//! # Helper types
//!
//! - [`Patch<T>`] -- tri-state value for partial-update (PATCH) payloads.
//! - [`FieldDiff<T>`] -- per-field before/after diff for inspecting and
//!   overriding changes inside hooks.
//! - [`MutationOp`] -- discriminant for create / update / delete.
//! - [`MutationContext`] -- carries actor identity, request ID, and
//!   timestamp into every hook invocation.

use serde::de::Deserializer;
use serde::{Deserialize, Serialize};

// ── Mutation operation & context ─────────────────────────────────────

/// The kind of mutation being performed on a repository record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MutationOp {
    /// A new record is being created.
    Create,
    /// An existing record is being updated.
    Update,
    /// An existing record is being deleted.
    Delete,
}

impl MutationOp {
    /// Returns the operation name as a static string slice.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Update => "update",
            Self::Delete => "delete",
        }
    }
}

impl std::fmt::Display for MutationOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Context available to mutation hooks.
///
/// Carries actor identity, request metadata, and timestamps so that
/// hook implementations can perform auditing, validation, or enrichment.
#[derive(Debug, Clone)]
pub struct MutationContext {
    /// The mutation operation type.
    pub op: MutationOp,
    /// Actor identity (user ID or service name). `None` for anonymous.
    pub actor: Option<String>,
    /// Correlation / request ID for tracing.
    pub request_id: Option<String>,
    /// Timestamp of the mutation.
    pub now: chrono::DateTime<chrono::Utc>,
}

impl MutationContext {
    /// Create a new context for the given operation.
    ///
    /// Auto-populates `now` with `Utc::now()` and `request_id` with a
    /// freshly generated UUID v4.
    #[must_use]
    pub fn new(op: MutationOp) -> Self {
        Self {
            op,
            actor: None,
            request_id: Some(uuid::Uuid::new_v4().to_string()),
            now: chrono::Utc::now(),
        }
    }
}

// ── Mutation hooks trait ─────────────────────────────────────────────

use crate::AutumnResult;
use std::future::Future;

/// Repository-scoped mutation lifecycle hooks.
///
/// All methods have default no-op implementations, so you only need to
/// override the callbacks you care about. Each method receives a
/// [`MutationContext`] (mutable for "before" hooks) and the relevant
/// model/changeset.
///
/// # Associated types
///
/// - `Model` -- the read model returned by queries (e.g., `User`).
/// - `NewModel` -- the insertable changeset (e.g., `NewUser`).
/// - `UpdateModel` -- the partial-update changeset (e.g., `UpdateUser`).
pub trait MutationHooks: Send + Sync + 'static {
    /// The read model (e.g., the `Queryable` struct).
    type Model: Send + Sync;
    /// The insertable changeset for new records.
    type NewModel: Send + Sync;
    /// The partial-update changeset.
    type UpdateModel: Send + Sync;

    /// Called before a new record is inserted.
    fn before_create(
        &self,
        _ctx: &mut MutationContext,
        _new: &mut Self::NewModel,
    ) -> impl Future<Output = AutumnResult<()>> + Send {
        async { Ok(()) }
    }

    /// Called before an existing record is updated.
    ///
    /// The `draft` holds the merged before/after state. Use per-field
    /// accessors (generated by `#[model]`) to inspect and rewrite:
    ///
    /// ```rust,ignore
    /// if draft.status().changed_to(&Status::Approved) {
    ///     draft.approved_at().set(Some(ctx.now));
    /// }
    /// ```
    fn before_update(
        &self,
        _ctx: &mut MutationContext,
        _draft: &mut UpdateDraft<Self::Model>,
    ) -> impl Future<Output = AutumnResult<()>> + Send
    where
        Self::Model: Clone,
    {
        async { Ok(()) }
    }

    /// Called before an existing record is deleted.
    fn before_delete(
        &self,
        _ctx: &mut MutationContext,
        _record: &Self::Model,
    ) -> impl Future<Output = AutumnResult<()>> + Send {
        async { Ok(()) }
    }
}

// ── Default no-op hooks ──────────────────────────────────────────────

/// Zero-cost no-op implementation of [`MutationHooks`].
///
/// Used by generated repository code when the user has not configured any
/// hooks. All methods use the trait defaults (immediate `Ok(())`).
pub struct NoHooks<M, N, U> {
    _phantom: std::marker::PhantomData<(M, N, U)>,
}

impl<M, N, U> Default for NoHooks<M, N, U> {
    fn default() -> Self {
        Self {
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<M, N, U> MutationHooks for NoHooks<M, N, U>
where
    M: Send + Sync + Clone + 'static,
    N: Send + Sync + 'static,
    U: Send + Sync + 'static,
{
    type Model = M;
    type NewModel = N;
    type UpdateModel = U;
}

/// Tri-state sparse update value.
///
/// `Patch<T>` distinguishes between "field not mentioned" ([`Unchanged`](Patch::Unchanged)),
/// "field explicitly set" ([`Set`](Patch::Set)), and "field explicitly cleared"
/// ([`Clear`](Patch::Clear), mapping to SQL `NULL`).
///
/// This is the building block for partial-update (PATCH) payloads where
/// omitting a field means "leave it alone" rather than "set it to its
/// default".
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Patch<T> {
    /// The field was not included in the update payload.
    #[default]
    Unchanged,
    /// The field was explicitly set to a new value.
    Set(T),
    /// The field was explicitly cleared (maps to SQL `NULL`).
    Clear,
}

impl<T> Patch<T> {
    /// Returns `true` if the field was not included in the update.
    #[must_use]
    pub const fn is_unchanged(&self) -> bool {
        matches!(self, Self::Unchanged)
    }

    /// Returns `true` if the field was explicitly set to a new value.
    #[must_use]
    pub const fn is_set(&self) -> bool {
        matches!(self, Self::Set(_))
    }

    /// Returns `true` if the field was explicitly cleared.
    #[must_use]
    pub const fn is_clear(&self) -> bool {
        matches!(self, Self::Clear)
    }

    /// Returns a reference to the inner value if [`Set`](Patch::Set), or `None`.
    #[must_use]
    pub const fn as_set(&self) -> Option<&T> {
        match self {
            Self::Set(v) => Some(v),
            _ => None,
        }
    }

    /// Converts into a nested `Option`:
    ///
    /// - `Set(v)` -> `Some(Some(v))`
    /// - `Clear` -> `Some(None)`
    /// - `Unchanged` -> `None`
    #[must_use]
    pub fn into_option(self) -> Option<Option<T>> {
        match self {
            Self::Set(v) => Some(Some(v)),
            Self::Clear => Some(None),
            Self::Unchanged => None,
        }
    }
}

impl<T: Serialize> Serialize for Patch<T> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Unchanged | Self::Clear => serializer.serialize_none(),
            Self::Set(v) => v.serialize(serializer),
        }
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // When this method is called, the field WAS present in the JSON.
        // Absent fields use the Default impl (→ Unchanged) via #[serde(default)].
        let opt: Option<T> = Option::deserialize(deserializer)?;
        Ok(opt.map_or_else(|| Self::Clear, Self::Set))
    }
}

/// Per-field before/after diff accessor for mutation hooks.
///
/// `FieldDiff<T>` holds the previous and proposed values for a single field,
/// allowing hook authors to inspect what changed and optionally override the
/// new value via [`set`](FieldDiff::set).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldDiff<T> {
    before: T,
    after: T,
}

impl<T: PartialEq> FieldDiff<T> {
    /// Create a new diff from before and after values.
    #[must_use]
    pub const fn new(before: T, after: T) -> Self {
        Self { before, after }
    }

    /// Reference to the value before the mutation.
    #[must_use]
    pub const fn before(&self) -> &T {
        &self.before
    }

    /// Reference to the (possibly overridden) value after the mutation.
    #[must_use]
    pub const fn after(&self) -> &T {
        &self.after
    }

    /// Returns `true` if the field value changed.
    #[must_use]
    pub fn changed(&self) -> bool {
        self.before != self.after
    }

    /// Returns `true` if the field value did not change.
    #[must_use]
    pub fn unchanged(&self) -> bool {
        self.before == self.after
    }

    /// Returns `true` if the field changed **and** the new value equals `value`.
    #[must_use]
    pub fn changed_to(&self, value: &T) -> bool {
        self.changed() && self.after == *value
    }

    /// Returns `true` if the field changed **and** the old value equals `value`.
    #[must_use]
    pub fn changed_from(&self, value: &T) -> bool {
        self.changed() && self.before == *value
    }

    /// Override the after value. Does not affect `before`.
    pub fn set(&mut self, value: T) {
        self.after = value;
    }
}

impl<T: PartialEq> FieldDiff<Option<T>> {
    /// Returns `true` if the field went from `None` to `Some`.
    #[must_use]
    pub const fn was_set(&self) -> bool {
        self.before.is_none() && self.after.is_some()
    }

    /// Returns `true` if the field went from `Some` to `None`.
    #[must_use]
    pub const fn was_cleared(&self) -> bool {
        self.before.is_some() && self.after.is_none()
    }
}

// ── UpdateDraft & DraftField ─────────────────────────────────────────

/// Merged before/after snapshot of a model for `before_update` hooks.
///
/// `UpdateDraft<T>` holds the original (`before`) and proposed (`after`)
/// state of a model. The `after` copy starts as a clone of `before` and
/// can be mutated via [`after_mut`](UpdateDraft::after_mut) or through
/// per-field [`DraftField`] accessors generated by `#[model]`.
///
/// # Usage
///
/// ```rust,ignore
/// let mut draft = UpdateDraft::new(existing_article);
/// // apply partial changes from the request …
/// draft.after_mut().title = new_title;
///
/// // per-field inspection via DraftField:
/// let title = DraftField::new(&draft.before().title, &mut draft.after_mut().title);
/// if title.changed() { /* … */ }
/// ```
#[derive(Debug, Clone)]
pub struct UpdateDraft<T: Clone> {
    /// The original (pre-mutation) model state.
    ///
    /// Public so that `#[model]`-generated per-field `DraftField` accessors
    /// can split-borrow `before` and `after` simultaneously.
    pub before: T,
    /// The proposed (post-mutation) model state.
    ///
    /// Public so that `#[model]`-generated per-field `DraftField` accessors
    /// can split-borrow `before` and `after` simultaneously.
    pub after: T,
}

impl<T: Clone> UpdateDraft<T> {
    /// Create a new draft from the current model state.
    ///
    /// Clones `before` into `after` so that `after` starts as an
    /// identical copy that can be selectively mutated.
    #[must_use]
    pub fn new(before: T) -> Self {
        let after = before.clone();
        Self { before, after }
    }

    /// Create a draft with explicit before and after values.
    ///
    /// Useful in tests or when changes have already been applied.
    #[must_use]
    pub const fn new_with_changes(before: T, after: T) -> Self {
        Self { before, after }
    }

    /// Reference to the original (pre-mutation) model.
    #[must_use]
    pub const fn before(&self) -> &T {
        &self.before
    }

    /// Reference to the proposed (post-mutation) model.
    #[must_use]
    pub const fn after(&self) -> &T {
        &self.after
    }

    /// Mutable reference to the proposed (post-mutation) model.
    ///
    /// Use this to apply changes before the update is persisted.
    #[must_use]
    pub const fn after_mut(&mut self) -> &mut T {
        &mut self.after
    }

    /// Consume the draft and return the proposed model.
    #[must_use]
    pub fn into_after(self) -> T {
        self.after
    }
}

/// Borrowing per-field accessor into an [`UpdateDraft`].
///
/// `DraftField` borrows `before` immutably and `after` mutably from the
/// parent draft. Because each `DraftField` is a temporary that drops at
/// statement end, you can inspect and mutate fields one at a time without
/// running into overlapping borrow issues:
///
/// ```rust,ignore
/// // generated by #[model]:
/// draft.status().changed_to(&Status::Published);
/// draft.title().set("New title".into());
/// ```
///
/// # Lifetime
///
/// `'a` ties the field references back to the `UpdateDraft` they came
/// from. The borrow is released when the `DraftField` is dropped.
#[derive(Debug)]
pub struct DraftField<'a, T> {
    before: &'a T,
    after: &'a mut T,
}

impl<'a, T> DraftField<'a, T> {
    /// Create a new field accessor borrowing from a draft.
    #[must_use]
    pub const fn new(before: &'a T, after: &'a mut T) -> Self {
        Self { before, after }
    }

    /// Reference to the original (pre-mutation) field value.
    #[must_use]
    pub const fn before(&self) -> &T {
        self.before
    }

    /// Reference to the proposed (post-mutation) field value.
    #[must_use]
    pub const fn after(&self) -> &T {
        self.after
    }

    /// Override the proposed value for this field.
    pub fn set(&mut self, value: T) {
        *self.after = value;
    }
}

impl<T: PartialEq> DraftField<'_, T> {
    /// Returns `true` if the field value changed.
    #[must_use]
    pub fn changed(&self) -> bool {
        self.before != self.after
    }

    /// Returns `true` if the field value did not change.
    #[must_use]
    pub fn unchanged(&self) -> bool {
        self.before == self.after
    }

    /// Returns `true` if the field changed **and** the new value equals `value`.
    #[must_use]
    pub fn changed_to(&self, value: &T) -> bool {
        self.changed() && *self.after == *value
    }

    /// Returns `true` if the field changed **and** the old value equals `value`.
    #[must_use]
    pub fn changed_from(&self, value: &T) -> bool {
        self.changed() && *self.before == *value
    }
}

impl<T: PartialEq> DraftField<'_, Option<T>> {
    /// Returns `true` if the field went from `None` to `Some`.
    #[must_use]
    pub const fn was_set(&self) -> bool {
        self.before.is_none() && self.after.is_some()
    }

    /// Returns `true` if the field went from `Some` to `None`.
    #[must_use]
    pub const fn was_cleared(&self) -> bool {
        self.before.is_some() && self.after.is_none()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Patch tests ──────────────────────────────────────────────

    #[test]
    fn patch_unchanged_is_default() {
        let p: Patch<String> = Patch::default();
        assert!(p.is_unchanged());
        assert!(!p.is_set());
        assert!(!p.is_clear());
    }

    #[test]
    fn patch_set_holds_value() {
        let p = Patch::Set("hello");
        assert!(p.is_set());
        assert!(!p.is_unchanged());
        assert!(!p.is_clear());
        assert_eq!(p.as_set(), Some(&"hello"));
    }

    #[test]
    fn patch_clear_is_clear() {
        let p: Patch<i32> = Patch::Clear;
        assert!(p.is_clear());
        assert!(!p.is_set());
        assert!(!p.is_unchanged());
    }

    #[test]
    fn patch_into_option_set() {
        assert_eq!(Patch::Set(42).into_option(), Some(Some(42)));
    }

    #[test]
    fn patch_into_option_clear() {
        assert_eq!(Patch::<i32>::Clear.into_option(), Some(None));
    }

    #[test]
    fn patch_into_option_unchanged() {
        assert_eq!(Patch::<i32>::Unchanged.into_option(), None);
    }

    // ── FieldDiff tests ──────────────────────────────────────────

    #[test]
    fn field_diff_unchanged() {
        let diff = FieldDiff::new(1, 1);
        assert!(diff.unchanged());
        assert!(!diff.changed());
    }

    #[test]
    fn field_diff_changed() {
        let diff = FieldDiff::new(1, 2);
        assert!(diff.changed());
    }

    #[test]
    fn field_diff_changed_to() {
        let diff = FieldDiff::new(1, 2);
        assert!(diff.changed_to(&2));
    }

    #[test]
    fn field_diff_changed_from() {
        let diff = FieldDiff::new(1, 2);
        assert!(diff.changed_from(&1));
    }

    #[test]
    fn field_diff_set_updates_after() {
        let mut diff = FieldDiff::new(1, 1);
        assert!(diff.unchanged());
        diff.set(5);
        assert!(diff.changed());
        assert_eq!(diff.after(), &5);
        assert_eq!(diff.before(), &1);
    }

    #[test]
    fn field_diff_option_was_set() {
        let diff = FieldDiff::new(None, Some(42));
        assert!(diff.was_set());
    }

    #[test]
    fn field_diff_option_was_cleared() {
        let diff = FieldDiff::new(Some(42), None);
        assert!(diff.was_cleared());
    }

    // ── MutationOp tests ────────────────────────────────────────────

    #[test]
    fn mutation_op_as_str() {
        assert_eq!(MutationOp::Create.as_str(), "create");
        assert_eq!(MutationOp::Update.as_str(), "update");
        assert_eq!(MutationOp::Delete.as_str(), "delete");
    }

    #[test]
    fn mutation_op_display() {
        assert_eq!(format!("{}", MutationOp::Create), "create");
    }

    // ── MutationContext tests ───────────────────────────────────────

    #[test]
    fn mutation_context_auto_populates() {
        let ctx = MutationContext::new(MutationOp::Create);
        assert!(ctx.actor.is_none());
        assert!(ctx.request_id.is_some());
        // UUID v4 format: 8-4-4-4-12 = 36 chars
        assert_eq!(ctx.request_id.as_ref().unwrap().len(), 36);
        assert!(matches!(ctx.op, MutationOp::Create));
    }

    #[test]
    fn mutation_context_with_actor() {
        let mut ctx = MutationContext::new(MutationOp::Update);
        ctx.actor = Some("user-123".into());
        assert_eq!(ctx.actor.as_deref(), Some("user-123"));
    }

    // ── MutationHooks / NoHooks tests ───────────────────────────────

    #[tokio::test]
    async fn no_hooks_all_methods_are_noop() {
        let hooks: NoHooks<(), (), ()> = NoHooks::default();
        let mut ctx = MutationContext::new(MutationOp::Create);
        let mut new_model = ();
        let model = ();
        let mut draft = UpdateDraft::new(());

        assert!(hooks.before_create(&mut ctx, &mut new_model).await.is_ok());
        assert!(hooks.before_update(&mut ctx, &mut draft).await.is_ok());
        assert!(hooks.before_delete(&mut ctx, &model).await.is_ok());
    }

    // ── Patch serde tests ──────────────────────────────────────────

    #[test]
    fn patch_serde_set_roundtrip() {
        let p = Patch::Set(42);
        let json = serde_json::to_string(&p).unwrap();
        assert_eq!(json, "42");
        let back: Patch<i32> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, Patch::Set(42));
    }

    #[test]
    fn patch_serde_clear_serializes_as_null() {
        let p: Patch<i32> = Patch::Clear;
        let json = serde_json::to_string(&p).unwrap();
        assert_eq!(json, "null");
    }

    #[test]
    fn patch_serde_null_deserializes_as_clear() {
        let p: Patch<i32> = serde_json::from_str("null").unwrap();
        assert_eq!(p, Patch::Clear);
    }

    #[test]
    fn patch_serde_absent_field_is_unchanged() {
        #[derive(Deserialize, PartialEq, Debug)]
        struct Payload {
            #[serde(default)]
            name: Patch<String>,
            #[serde(default)]
            age: Patch<i32>,
        }
        let p: Payload = serde_json::from_str(r#"{"name": "Alice"}"#).unwrap();
        assert_eq!(p.name, Patch::Set("Alice".to_string()));
        assert_eq!(p.age, Patch::Unchanged);
    }

    #[test]
    fn patch_serde_explicit_null_is_clear() {
        #[derive(Deserialize, PartialEq, Debug)]
        struct Payload {
            #[serde(default)]
            name: Patch<String>,
        }
        let p: Payload = serde_json::from_str(r#"{"name": null}"#).unwrap();
        assert_eq!(p.name, Patch::Clear);
    }

    // ── UpdateDraft tests ───────────────────────────────────────────

    #[test]
    fn update_draft_before_after() {
        let draft = UpdateDraft::new_with_changes("old".to_string(), "new".to_string());
        assert_eq!(draft.before(), "old");
        assert_eq!(draft.after(), "new");
    }

    #[test]
    fn update_draft_into_after() {
        let draft = UpdateDraft::new_with_changes(1, 2);
        assert_eq!(draft.into_after(), 2);
    }

    #[test]
    fn update_draft_new_clones() {
        let draft = UpdateDraft::new(42);
        assert_eq!(draft.before(), &42);
        assert_eq!(draft.after(), &42);
    }

    #[test]
    fn update_draft_after_mut() {
        let mut draft = UpdateDraft::new_with_changes(1, 2);
        *draft.after_mut() = 3;
        assert_eq!(draft.after(), &3);
    }

    // ── DraftField tests ────────────────────────────────────────────

    #[test]
    fn draft_field_before_after() {
        let before = 1;
        let mut after = 2;
        let field = DraftField::new(&before, &mut after);
        assert_eq!(field.before(), &1);
        assert_eq!(field.after(), &2);
    }

    #[test]
    fn draft_field_changed() {
        let before = 1;
        let mut after = 2;
        let field = DraftField::new(&before, &mut after);
        assert!(field.changed());
        assert!(!field.unchanged());
    }

    #[test]
    fn draft_field_unchanged() {
        let before = 1;
        let mut after = 1;
        let field = DraftField::new(&before, &mut after);
        assert!(field.unchanged());
        assert!(!field.changed());
    }

    #[test]
    fn draft_field_changed_to() {
        let before = "draft".to_string();
        let mut after = "published".to_string();
        let field = DraftField::new(&before, &mut after);
        assert!(field.changed_to(&"published".to_string()));
        assert!(!field.changed_to(&"draft".to_string()));
    }

    #[test]
    fn draft_field_changed_from() {
        let before = "draft".to_string();
        let mut after = "published".to_string();
        let field = DraftField::new(&before, &mut after);
        assert!(field.changed_from(&"draft".to_string()));
        assert!(!field.changed_from(&"published".to_string()));
    }

    #[test]
    fn draft_field_set_mutates_after() {
        let before = 10;
        let mut after = 10;
        {
            let mut field = DraftField::new(&before, &mut after);
            assert!(field.unchanged());
            field.set(20);
            assert!(field.changed());
            assert_eq!(field.after(), &20);
        }
        // Verify mutation propagated to the original variable
        assert_eq!(after, 20);
    }

    #[test]
    fn draft_field_option_was_set() {
        let before: Option<i32> = None;
        let mut after: Option<i32> = Some(42);
        let field = DraftField::new(&before, &mut after);
        assert!(field.was_set());
        assert!(!field.was_cleared());
    }

    #[test]
    fn draft_field_option_was_cleared() {
        let before: Option<i32> = Some(42);
        let mut after: Option<i32> = None;
        let field = DraftField::new(&before, &mut after);
        assert!(field.was_cleared());
        assert!(!field.was_set());
    }
}