auditlog 0.1.0

Audit trail for your data models — an ORM-agnostic core with a pluggable, async sqlx backend (SQLite & Postgres).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Behavioral tests covering auditlog's change-set shapes, versioning, filters, comments,
//! redaction, max_audits combine, attribution, enable/disable, revisions, undo, and associated
//! audits.
//!
//! These run against the real SQLite [`SqlxBackend`], exercising the full path from change
//! computation through serialization and back. Process-global state (the master switch and the
//! global `max_audits`) is exercised in `tests/global_state.rs` instead, so this file is safe to
//! run in parallel.

use auditlog::{
    Action, Actor, AuditError, AuditId, AuditOptions, Auditable, SqlxBackend, UndoPlan, ValueMap,
    as_user, with_auditing, without_auditing,
};
use serde_json::{Value, json};

// ---------- helpers ----------

async fn backend() -> SqlxBackend {
    let b = SqlxBackend::connect_sqlite("sqlite::memory:")
        .await
        .unwrap();
    b.migrate().await.unwrap();
    b
}

fn build_attrs(
    id: i64,
    name: &Option<String>,
    status: i64,
    logins: i64,
    password: &Option<String>,
) -> ValueMap {
    let mut m = ValueMap::new();
    m.insert("id".into(), json!(id));
    m.insert(
        "name".into(),
        name.clone().map(Value::from).unwrap_or(Value::Null),
    );
    m.insert("status".into(), json!(status));
    m.insert("logins".into(), json!(logins));
    m.insert(
        "password".into(),
        password.clone().map(Value::from).unwrap_or(Value::Null),
    );
    m
}

/// Define a model type with the five standard columns and a given type name + options.
macro_rules! model {
    ($name:ident, $type_name:expr, $opts:expr) => {
        #[derive(Clone, Default)]
        #[allow(dead_code)]
        struct $name {
            id: i64,
            name: Option<String>,
            status: i64,
            logins: i64,
            password: Option<String>,
        }
        impl Auditable for $name {
            fn auditable_type() -> &'static str {
                $type_name
            }
            fn auditable_id(&self) -> AuditId {
                self.id.into()
            }
            fn audited_attributes(&self) -> ValueMap {
                build_attrs(
                    self.id,
                    &self.name,
                    self.status,
                    self.logins,
                    &self.password,
                )
            }
            fn audit_options() -> AuditOptions {
                $opts
            }
        }
        #[allow(dead_code)]
        impl $name {
            fn named(id: i64, name: &str) -> Self {
                $name {
                    id,
                    name: Some(name.to_string()),
                    ..Default::default()
                }
            }
        }
    };
}

model!(User, "User", AuditOptions::default());
model!(
    OnlyName,
    "OnlyName",
    AuditOptions::builder().only(["name"]).build()
);
model!(
    ExceptPassword,
    "ExceptPassword",
    AuditOptions::builder().except(["password"]).build()
);
model!(
    Commented,
    "Commented",
    AuditOptions::builder().comment_required(true).build()
);
model!(
    NoUpdateOnly,
    "NoUpdateOnly",
    AuditOptions::builder()
        .update_with_comment_only(false)
        .build()
);
model!(
    Capped,
    "Capped",
    AuditOptions::builder().max_audits(2).build()
);
model!(
    Redacted,
    "Redacted",
    AuditOptions::builder().redacted(["password"]).build()
);
model!(
    RedactedCustom,
    "RedactedCustom",
    AuditOptions::builder()
        .redacted(["password"])
        .redaction_value(json!("***"))
        .build()
);
model!(
    Encrypted,
    "Encrypted",
    AuditOptions::builder().encrypted(["password"]).build()
);
model!(
    OnlyCreate,
    "OnlyCreate",
    AuditOptions::builder().on([Action::Create]).build()
);
model!(
    OnlyUpdate,
    "OnlyUpdate",
    AuditOptions::builder().on([Action::Update]).build()
);
model!(Disablable, "Disablable", AuditOptions::default());
model!(
    Collapse,
    "Collapse",
    AuditOptions::builder().max_audits(0).build()
);

// ---------- change-set shape ----------

#[tokio::test]
async fn create_stores_single_values_snapshot() {
    let b = backend().await;
    let u = User::named(1, "Brandon");
    let audit = u.audited_create(&b).await.unwrap().unwrap();

    assert_eq!(audit.action, Action::Create);
    assert_eq!(audit.version, 1);
    // create stores single values, not [old, new] pairs; id is excluded by default.
    assert_eq!(audit.audited_changes.0.get("name"), Some(&json!("Brandon")));
    assert!(!audit.audited_changes.0.contains_key("id"));
    let na = audit.new_attributes();
    assert_eq!(na.get("name"), Some(&json!("Brandon")));
}

#[tokio::test]
async fn update_stores_old_new_pairs() {
    let b = backend().await;
    let old = User::named(1, "Brandon");
    old.audited_create(&b).await.unwrap();

    let new = User::named(1, "Changed");
    let audit = new.audited_update(&b, &old).await.unwrap().unwrap();

    assert_eq!(audit.action, Action::Update);
    assert_eq!(audit.version, 2);
    assert_eq!(
        audit.audited_changes.0.get("name"),
        Some(&json!(["Brandon", "Changed"]))
    );
    assert_eq!(audit.new_attributes().get("name"), Some(&json!("Changed")));
    assert_eq!(audit.old_attributes().get("name"), Some(&json!("Brandon")));
}

#[tokio::test]
async fn destroy_stores_full_snapshot_like_create() {
    let b = backend().await;
    let u = User::named(1, "Brandon");
    u.audited_create(&b).await.unwrap();
    let audit = u.audited_destroy(&b).await.unwrap().unwrap();

    assert_eq!(audit.action, Action::Destroy);
    assert_eq!(audit.version, 2);
    // single values, full snapshot
    assert_eq!(audit.audited_changes.0.get("name"), Some(&json!("Brandon")));
    assert_eq!(audit.audited_changes.0.get("status"), Some(&json!(0)));
}

#[tokio::test]
async fn unchanged_update_writes_no_audit() {
    let b = backend().await;
    let old = User::named(1, "Brandon");
    old.audited_create(&b).await.unwrap();
    // identical -> no diff -> no audit
    let same = User::named(1, "Brandon");
    assert!(same.audited_update(&b, &old).await.unwrap().is_none());
    assert_eq!(User::audits(&b, 1).await.unwrap().len(), 1);
}

// ---------- versioning ----------

#[tokio::test]
async fn version_increments_across_action_types() {
    let b = backend().await;
    let mut u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    let old = u.clone();
    u.name = Some("B".into());
    u.audited_update(&b, &old).await.unwrap();
    u.audited_destroy(&b).await.unwrap();

    let audits = User::audits(&b, 1).await.unwrap();
    let versions: Vec<i32> = audits.iter().map(|a| a.version).collect();
    assert_eq!(versions, vec![1, 2, 3]);
    let actions: Vec<Action> = audits.iter().map(|a| a.action).collect();
    assert_eq!(
        actions,
        vec![Action::Create, Action::Update, Action::Destroy]
    );
}

// ---------- on: filtering ----------

#[tokio::test]
async fn on_create_only_skips_updates_and_destroys() {
    let b = backend().await;
    let mut u = OnlyCreate {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    assert!(u.audited_create(&b).await.unwrap().is_some());
    let old = u.clone();
    u.name = Some("B".into());
    assert!(u.audited_update(&b, &old).await.unwrap().is_none());
    assert!(u.audited_destroy(&b).await.unwrap().is_none());
    assert_eq!(OnlyCreate::audits(&b, 1).await.unwrap().len(), 1);
}

#[tokio::test]
async fn on_update_only_skips_creates() {
    let b = backend().await;
    let old = OnlyUpdate {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    assert!(old.audited_create(&b).await.unwrap().is_none());
    let new = OnlyUpdate {
        id: 1,
        name: Some("B".into()),
        ..Default::default()
    };
    assert!(new.audited_update(&b, &old).await.unwrap().is_some());
    let audits = OnlyUpdate::audits(&b, 1).await.unwrap();
    assert_eq!(audits.len(), 1);
    // first audit is the update, version starts at... max+1 with no prior = 1
    assert_eq!(audits[0].action, Action::Update);
}

// ---------- only / except ----------

#[tokio::test]
async fn only_audits_listed_columns() {
    let b = backend().await;
    let u = OnlyName {
        id: 1,
        name: Some("A".into()),
        status: 5,
        logins: 9,
        password: Some("secret".into()),
    };
    let audit = u.audited_create(&b).await.unwrap().unwrap();
    let keys: Vec<&String> = audit.audited_changes.0.keys().collect();
    assert_eq!(keys, vec![&"name".to_string()]);
}

#[tokio::test]
async fn except_excludes_listed_columns_on_create_and_destroy() {
    let b = backend().await;
    let u = ExceptPassword {
        id: 1,
        name: Some("A".into()),
        password: Some("secret".into()),
        ..Default::default()
    };
    let audit = u.audited_create(&b).await.unwrap().unwrap();
    assert!(!audit.audited_changes.0.contains_key("password"));
    assert!(audit.audited_changes.0.contains_key("name"));
    let d = u.audited_destroy(&b).await.unwrap().unwrap();
    assert!(!d.audited_changes.0.contains_key("password"));
}

// ---------- redaction / encryption ----------

#[tokio::test]
async fn redacted_create_is_single_placeholder() {
    let b = backend().await;
    let u = Redacted {
        id: 1,
        name: Some("A".into()),
        password: Some("secret".into()),
        ..Default::default()
    };
    let audit = u.audited_create(&b).await.unwrap().unwrap();
    assert_eq!(
        audit.audited_changes.0.get("password"),
        Some(&json!("[REDACTED]"))
    );
}

#[tokio::test]
async fn redacted_update_replaces_both_sides() {
    let b = backend().await;
    let old = Redacted {
        id: 1,
        password: Some("old".into()),
        ..Default::default()
    };
    old.audited_create(&b).await.unwrap();
    let new = Redacted {
        id: 1,
        password: Some("new".into()),
        ..Default::default()
    };
    let audit = new.audited_update(&b, &old).await.unwrap().unwrap();
    assert_eq!(
        audit.audited_changes.0.get("password"),
        Some(&json!(["[REDACTED]", "[REDACTED]"]))
    );
}

#[tokio::test]
async fn redacted_unchanged_column_absent_from_update() {
    let b = backend().await;
    let old = Redacted {
        id: 1,
        name: Some("A".into()),
        password: Some("same".into()),
        ..Default::default()
    };
    old.audited_create(&b).await.unwrap();
    let new = Redacted {
        id: 1,
        name: Some("B".into()),
        password: Some("same".into()),
        ..Default::default()
    };
    let audit = new.audited_update(&b, &old).await.unwrap().unwrap();
    assert!(!audit.audited_changes.0.contains_key("password"));
    assert!(audit.audited_changes.0.contains_key("name"));
}

#[tokio::test]
async fn custom_redaction_value_used_verbatim() {
    let b = backend().await;
    let u = RedactedCustom {
        id: 1,
        password: Some("secret".into()),
        ..Default::default()
    };
    let audit = u.audited_create(&b).await.unwrap().unwrap();
    assert_eq!(audit.audited_changes.0.get("password"), Some(&json!("***")));
}

#[tokio::test]
async fn encrypted_columns_use_filtered_placeholder() {
    let b = backend().await;
    let u = Encrypted {
        id: 1,
        password: Some("secret".into()),
        ..Default::default()
    };
    let audit = u.audited_create(&b).await.unwrap().unwrap();
    assert_eq!(
        audit.audited_changes.0.get("password"),
        Some(&json!("[FILTERED]"))
    );
}

// ---------- comments ----------

#[tokio::test]
async fn comment_only_update_writes_audit_by_default() {
    let b = backend().await;
    let old = User::named(1, "A");
    old.audited_create(&b).await.unwrap();
    // no attribute change, but a comment is present
    let same = User::named(1, "A");
    let audit = same
        .audited_update_with_comment(&b, &old, "just a note")
        .await
        .unwrap();
    assert!(audit.is_some());
    assert_eq!(audit.unwrap().comment.as_deref(), Some("just a note"));
}

#[tokio::test]
async fn comment_only_update_skipped_when_update_with_comment_only_false() {
    let b = backend().await;
    let old = NoUpdateOnly {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    old.audited_create(&b).await.unwrap();
    let same = NoUpdateOnly {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    let audit = same
        .audited_update_with_comment(&b, &same, "note")
        .await
        .unwrap();
    assert!(audit.is_none());
}

#[tokio::test]
async fn comment_required_blocks_create_without_comment() {
    let b = backend().await;
    let u = Commented {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    let err = u.audited_create(&b).await.unwrap_err();
    assert!(matches!(
        err,
        AuditError::CommentRequired {
            action: Action::Create
        }
    ));
    // with comment it succeeds
    assert!(
        u.audited_create_with_comment(&b, "because")
            .await
            .unwrap()
            .is_some()
    );
}

#[tokio::test]
async fn comment_required_aborts_destroy_without_comment() {
    let b = backend().await;
    let u = Commented {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    u.audited_create_with_comment(&b, "create").await.unwrap();
    let err = u.audited_destroy(&b).await.unwrap_err();
    assert!(matches!(
        err,
        AuditError::CommentRequired {
            action: Action::Destroy
        }
    ));
}

#[tokio::test]
async fn comment_required_allows_unchanged_update_without_comment() {
    let b = backend().await;
    let old = Commented {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    old.audited_create_with_comment(&b, "c").await.unwrap();
    // no audited change -> no comment required, no audit, no error
    let same = Commented {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    assert!(same.audited_update(&b, &old).await.unwrap().is_none());
}

// ---------- max_audits combine ----------

#[tokio::test]
async fn max_audits_combines_oldest_and_preserves_versions() {
    let b = backend().await;
    let mut u = Capped {
        id: 1,
        name: Some("Foobar".into()),
        ..Default::default()
    };
    u.audited_create(&b).await.unwrap(); // v1

    let old = u.clone();
    u.name = Some("Awesome".into());
    u.audited_update_with_comment(&b, &old, "first audit comment")
        .await
        .unwrap(); // v2

    let old2 = u.clone();
    u.status = 7;
    u.audited_update_with_comment(&b, &old2, "second audit comment")
        .await
        .unwrap(); // v3

    let audits = Capped::audits(&b, 1).await.unwrap();
    // pruned down to max_audits = 2, surviving versions keep original numbers [2, 3]
    assert_eq!(audits.len(), 2);
    assert_eq!(
        audits.iter().map(|a| a.version).collect::<Vec<_>>(),
        vec![2, 3]
    );

    // the surviving oldest audit merges v1+v2 changes and annotates its comment
    let first = &audits[0];
    assert_eq!(first.version, 2);
    assert_eq!(
        first.audited_changes.0.get("name"),
        Some(&json!(["Foobar", "Awesome"]))
    );
    let comment = first.comment.as_deref().unwrap_or("");
    assert!(comment.contains("first audit comment"));
    assert!(comment.contains("result of multiple"));
}

#[tokio::test]
async fn max_audits_zero_collapses_history_to_one() {
    // A max_audits of 0 collapses all history into the newest audit on every write.
    let b = backend().await;
    let mut u = Collapse {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    u.audited_create(&b).await.unwrap();
    let o1 = u.clone();
    u.name = Some("B".into());
    u.audited_update(&b, &o1).await.unwrap();
    let o2 = u.clone();
    u.name = Some("C".into());
    u.audited_update(&b, &o2).await.unwrap();

    let audits = Collapse::audits(&b, 1).await.unwrap();
    assert_eq!(audits.len(), 1);
    assert_eq!(audits[0].version, 3);
}

// ---------- STI inheritance column ----------

struct Vehicle {
    id: i64,
    kind: String,
    name: String,
}
impl Auditable for Vehicle {
    fn auditable_type() -> &'static str {
        "Vehicle"
    }
    fn auditable_id(&self) -> AuditId {
        self.id.into()
    }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("type".into(), json!(self.kind));
        m.insert("name".into(), json!(self.name));
        m
    }
    fn audit_options() -> AuditOptions {
        AuditOptions::default()
    }
    fn inheritance_column() -> Option<&'static str> {
        Some("type")
    }
}

#[tokio::test]
async fn sti_inheritance_column_is_not_audited() {
    let b = backend().await;
    let v = Vehicle {
        id: 1,
        kind: "Car".into(),
        name: "Beetle".into(),
    };
    let audit = v.audited_create(&b).await.unwrap().unwrap();
    assert!(!audit.audited_changes.0.contains_key("type"));
    assert!(audit.audited_changes.0.contains_key("name"));
}

// ---------- array-typed redacted column ----------

struct Tagged {
    id: i64,
    tags: Vec<String>,
}
impl Auditable for Tagged {
    fn auditable_type() -> &'static str {
        "Tagged"
    }
    fn auditable_id(&self) -> AuditId {
        self.id.into()
    }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("tags".into(), json!(self.tags));
        m
    }
    fn audit_options() -> AuditOptions {
        AuditOptions::builder().redacted(["tags"]).build()
    }
}

#[tokio::test]
async fn array_typed_redacted_column_masks_element_wise_on_create() {
    let b = backend().await;
    let t = Tagged {
        id: 1,
        tags: vec!["a".into(), "b".into(), "c".into()],
    };
    let audit = t.audited_create(&b).await.unwrap().unwrap();
    // arity preserved: a 3-element array masks to 3 placeholders, not a single scalar
    assert_eq!(
        audit.audited_changes.0.get("tags"),
        Some(&json!(["[REDACTED]", "[REDACTED]", "[REDACTED]"]))
    );
}

// ---------- user attribution ----------

#[tokio::test]
async fn as_user_with_record_sets_polymorphic_user() {
    let b = backend().await;
    let u = User::named(1, "A");
    as_user(Actor::record("Admin", 99), async {
        u.audited_create(&b).await
    })
    .await
    .unwrap();

    let audit = &User::audits(&b, 1).await.unwrap()[0];
    assert_eq!(audit.user_type.as_deref(), Some("Admin"));
    assert_eq!(audit.user_id.as_ref().map(|i| i.as_str()), Some("99"));
    assert_eq!(audit.username, None);
    assert_eq!(audit.user(), Some(Actor::record("Admin", 99)));
}

#[tokio::test]
async fn as_user_with_string_sets_username() {
    let b = backend().await;
    let u = User::named(1, "A");
    as_user("import job", async { u.audited_create(&b).await })
        .await
        .unwrap();

    let audit = &User::audits(&b, 1).await.unwrap()[0];
    assert_eq!(audit.username.as_deref(), Some("import job"));
    assert_eq!(audit.user_id, None);
    assert_eq!(audit.user_type, None);
}

#[tokio::test]
async fn as_user_nests_and_restores() {
    let b = backend().await;
    let u1 = User::named(1, "A");
    let u2 = User::named(2, "B");
    let u3 = User::named(3, "C");

    as_user("outer", async {
        u1.audited_create(&b).await.unwrap();
        as_user("inner", async { u2.audited_create(&b).await })
            .await
            .unwrap();
        u3.audited_create(&b).await.unwrap();
    })
    .await;

    let a1 = &User::audits(&b, 1).await.unwrap()[0];
    let a2 = &User::audits(&b, 2).await.unwrap()[0];
    let a3 = &User::audits(&b, 3).await.unwrap()[0];
    assert_eq!(a1.username.as_deref(), Some("outer"));
    assert_eq!(a2.username.as_deref(), Some("inner"));
    assert_eq!(a3.username.as_deref(), Some("outer")); // restored after inner
}

#[tokio::test]
async fn request_uuid_always_present() {
    let b = backend().await;
    let u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    let audit = &User::audits(&b, 1).await.unwrap()[0];
    assert!(audit.request_uuid.as_deref().is_some_and(|s| !s.is_empty()));
    // no context -> no remote address
    assert_eq!(audit.remote_address, None);
}

// ---------- enable / disable ----------

#[tokio::test]
async fn without_auditing_scope_suppresses() {
    let b = backend().await;
    let u = User::named(1, "A");
    without_auditing(async { u.audited_create(&b).await })
        .await
        .unwrap();
    assert_eq!(User::audits(&b, 1).await.unwrap().len(), 0);

    // outside the scope it audits again
    u.audited_create(&b).await.unwrap();
    assert_eq!(User::audits(&b, 1).await.unwrap().len(), 1);
}

#[tokio::test]
async fn with_auditing_forces_enable_for_disabled_type() {
    let b = backend().await;
    Disablable::disable_auditing();
    let u = Disablable {
        id: 1,
        name: Some("A".into()),
        ..Default::default()
    };
    // disabled -> no audit
    assert!(u.audited_create(&b).await.unwrap().is_none());
    // with_auditing forces it on within the scope
    with_auditing(async { u.audited_create(&b).await })
        .await
        .unwrap();
    assert_eq!(Disablable::audits(&b, 1).await.unwrap().len(), 1);
    Disablable::enable_auditing();
}

#[tokio::test]
async fn without_auditing_is_task_isolated() {
    let b = backend().await;
    let a = User::named(1, "A"); // suppressed
    let c = User::named(2, "C"); // not suppressed
    // join! polls both futures on one task; the scope only wraps `a`'s future.
    let (_x, _y) = tokio::join!(
        without_auditing(async { a.audited_create(&b).await.unwrap() }),
        async { c.audited_create(&b).await.unwrap() },
    );
    assert_eq!(User::audits(&b, 1).await.unwrap().len(), 0);
    assert_eq!(User::audits(&b, 2).await.unwrap().len(), 1);
}

// ---------- if / unless ----------

struct Conditional {
    id: i64,
    active: bool,
    name: String,
}

impl Auditable for Conditional {
    fn auditable_type() -> &'static str {
        "Conditional"
    }
    fn auditable_id(&self) -> AuditId {
        self.id.into()
    }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("name".into(), json!(self.name));
        m
    }
    fn audit_options() -> AuditOptions {
        AuditOptions::default()
    }
    fn audit_if(&self) -> bool {
        self.active
    }
}

#[tokio::test]
async fn instance_if_condition_gates_auditing() {
    let b = backend().await;
    let inactive = Conditional {
        id: 1,
        active: false,
        name: "A".into(),
    };
    assert!(inactive.audited_create(&b).await.unwrap().is_none());

    let active = Conditional {
        id: 2,
        active: true,
        name: "B".into(),
    };
    assert!(active.audited_create(&b).await.unwrap().is_some());
}

// ---------- revisions ----------

#[tokio::test]
async fn revisions_reconstruct_each_version() {
    let b = backend().await;
    let mut u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    let o1 = u.clone();
    u.name = Some("B".into());
    u.audited_update(&b, &o1).await.unwrap();
    let o2 = u.clone();
    u.name = Some("C".into());
    u.audited_update(&b, &o2).await.unwrap();

    let revs = User::revisions(&b, 1).await.unwrap();
    assert_eq!(revs.len(), 3);
    assert_eq!(revs[0].attributes.get("name"), Some(&json!("A")));
    assert_eq!(revs[1].attributes.get("name"), Some(&json!("B")));
    assert_eq!(revs[2].attributes.get("name"), Some(&json!("C")));
    assert_eq!(revs[0].version, 1);
    assert_eq!(revs[2].version, 3);
}

#[tokio::test]
async fn revision_at_version_and_previous_and_out_of_range() {
    let b = backend().await;
    let mut u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    let o1 = u.clone();
    u.name = Some("B".into());
    u.audited_update(&b, &o1).await.unwrap();
    let o2 = u.clone();
    u.name = Some("C".into());
    u.audited_update(&b, &o2).await.unwrap();

    assert_eq!(
        User::revision(&b, 1, 1)
            .await
            .unwrap()
            .unwrap()
            .attributes
            .get("name"),
        Some(&json!("A"))
    );
    assert_eq!(
        User::revision(&b, 1, 2)
            .await
            .unwrap()
            .unwrap()
            .attributes
            .get("name"),
        Some(&json!("B"))
    );
    // out of range -> None
    assert!(User::revision(&b, 1, 4).await.unwrap().is_none());
    // previous = second-most-recent (v2 -> "B")
    assert_eq!(
        User::revision_previous(&b, 1)
            .await
            .unwrap()
            .unwrap()
            .attributes
            .get("name"),
        Some(&json!("B"))
    );
}

#[tokio::test]
async fn destroyed_record_reconstructs_as_new_record() {
    let b = backend().await;
    let u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    u.audited_destroy(&b).await.unwrap();

    // latest revision corresponds to the destroy and is flagged as a new (unsaved) record
    let revs = User::revisions(&b, 1).await.unwrap();
    let last = revs.last().unwrap();
    assert!(last.new_record);
    assert_eq!(last.attributes.get("name"), Some(&json!("A")));
}

// ---------- undo ----------

#[tokio::test]
async fn undo_plans_reverse_each_action() {
    let b = backend().await;
    let mut u = User::named(1, "A");
    let create = u.audited_create(&b).await.unwrap().unwrap();
    assert_eq!(create.undo_plan().unwrap(), UndoPlan::Delete);

    let old = u.clone();
    u.name = Some("B".into());
    let update = u.audited_update(&b, &old).await.unwrap().unwrap();
    match update.undo_plan().unwrap() {
        UndoPlan::Restore(attrs) => assert_eq!(attrs.get("name"), Some(&json!("A"))),
        other => panic!("expected Restore, got {other:?}"),
    }

    let destroy = u.audited_destroy(&b).await.unwrap().unwrap();
    match destroy.undo_plan().unwrap() {
        UndoPlan::Recreate(attrs) => assert_eq!(attrs.get("name"), Some(&json!("B"))),
        other => panic!("expected Recreate, got {other:?}"),
    }
}

// ---------- scopes ----------

#[tokio::test]
async fn scope_query_filters_by_action_and_order() {
    let b = backend().await;
    let mut u = User::named(1, "A");
    u.audited_create(&b).await.unwrap();
    let o1 = u.clone();
    u.name = Some("B".into());
    u.audited_update(&b, &o1).await.unwrap();
    let o2 = u.clone();
    u.name = Some("C".into());
    u.audited_update(&b, &o2).await.unwrap();

    let updates = User::query(&b, 1).updates().fetch().await.unwrap();
    assert_eq!(updates.len(), 2);
    assert!(updates.iter().all(|a| a.action == Action::Update));

    let creates = User::query(&b, 1).creates().fetch().await.unwrap();
    assert_eq!(creates.len(), 1);

    let desc = User::query(&b, 1)
        .descending()
        .limit(1)
        .fetch()
        .await
        .unwrap();
    assert_eq!(desc[0].version, 3);

    let from2 = User::query(&b, 1).from_version(2).fetch().await.unwrap();
    assert_eq!(
        from2.iter().map(|a| a.version).collect::<Vec<_>>(),
        vec![2, 3]
    );
}

// ---------- associated audits ----------

struct Company {
    id: i64,
    name: String,
}
impl Auditable for Company {
    fn auditable_type() -> &'static str {
        "Company"
    }
    fn auditable_id(&self) -> AuditId {
        self.id.into()
    }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("name".into(), json!(self.name));
        m
    }
    fn audit_options() -> AuditOptions {
        AuditOptions::default()
    }
}

struct Employee {
    id: i64,
    name: String,
    company_id: i64,
}
impl Auditable for Employee {
    fn auditable_type() -> &'static str {
        "Employee"
    }
    fn auditable_id(&self) -> AuditId {
        self.id.into()
    }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("name".into(), json!(self.name));
        m.insert("company_id".into(), json!(self.company_id));
        m
    }
    fn audit_options() -> AuditOptions {
        AuditOptions::builder().associated_with("Company").build()
    }
    fn audit_associated(&self) -> Option<(String, AuditId)> {
        Some(("Company".to_string(), self.company_id.into()))
    }
}

#[tokio::test]
async fn associated_audits_are_recorded_and_queryable() {
    let b = backend().await;
    let company = Company {
        id: 10,
        name: "Acme".into(),
    };
    company.audited_create(&b).await.unwrap();

    let emp = Employee {
        id: 1,
        name: "Alice".into(),
        company_id: 10,
    };
    let audit = emp.audited_create(&b).await.unwrap().unwrap();
    assert_eq!(audit.associated_type.as_deref(), Some("Company"));
    assert_eq!(audit.associated_id.as_ref().map(|i| i.as_str()), Some("10"));

    // the company sees the employee's audit as an associated audit
    let assoc = Company::associated_audits(&b, 10).await.unwrap();
    assert_eq!(assoc.len(), 1);
    assert_eq!(assoc[0].auditable_type, "Employee");

    // own + associated unions both, newest first
    let combined = Company::own_and_associated_audits(&b, 10).await.unwrap();
    assert_eq!(combined.len(), 2);
}