cf-mini-chat 0.1.29

Mini-chat module: multi-tenant AI chat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
use std::sync::Arc;

use modkit_security::AccessScope;
use uuid::Uuid;

use crate::domain::repos::{ChatRepository, MessageRepository, TurnRepository};
use crate::domain::service::test_helpers::TestMetrics;
use crate::domain::service::test_helpers::*;
use crate::domain::service::turn_service::MutationError;
use crate::domain::service::{AuditEnvelope, TurnService};
use crate::infra::db::entity::chat_turn::TurnState;
use crate::infra::db::repo;
use std::sync::atomic::Ordering;

// ════════════════════════════════════════════════════════════════════════════
// Helpers
// ════════════════════════════════════════════════════════════════════════════

async fn setup() -> (
    TurnService<
        repo::turn_repo::TurnRepository,
        repo::message_repo::MessageRepository,
        repo::chat_repo::ChatRepository,
        repo::message_attachment_repo::MessageAttachmentRepository,
    >,
    modkit_security::SecurityContext,
    Uuid, // chat_id
    Uuid, // tenant_id
) {
    let db = inmem_db().await;
    let db = mock_db_provider(db);
    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let chat_repo = Arc::new(repo::chat_repo::ChatRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));
    let turn_repo = Arc::new(repo::turn_repo::TurnRepository);
    let message_repo = Arc::new(repo::message_repo::MessageRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));

    // Create a chat first
    let chat_id = Uuid::now_v7();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db.conn().unwrap();
    chat_repo
        .create(
            &conn,
            &scope,
            crate::domain::models::Chat {
                id: chat_id,
                tenant_id,
                user_id: ctx.subject_id(),
                model: "gpt-5.2".to_owned(),
                title: Some("Test chat".to_owned()),
                is_temporary: false,
                created_at: time::OffsetDateTime::now_utc(),
                updated_at: time::OffsetDateTime::now_utc(),
            },
        )
        .await
        .unwrap();

    let svc = TurnService::new(
        Arc::clone(&db),
        turn_repo,
        message_repo,
        chat_repo,
        Arc::new(crate::infra::db::repo::message_attachment_repo::MessageAttachmentRepository),
        mock_enforcer(),
        Arc::new(RecordingOutboxEnqueuer::new()),
        Arc::new(crate::domain::ports::metrics::NoopMetrics),
    );

    (svc, ctx, chat_id, tenant_id)
}

/// Create a completed turn with a user message. Returns the `request_id`.
async fn create_completed_turn(
    db: &crate::domain::service::DbProvider,
    turn_repo: &impl TurnRepository,
    message_repo: &impl crate::domain::repos::MessageRepository,
    tenant_id: Uuid,
    chat_id: Uuid,
    user_id: Uuid,
) -> Uuid {
    create_completed_turn_inner(
        db,
        turn_repo,
        message_repo,
        tenant_id,
        chat_id,
        user_id,
        false,
    )
    .await
}

/// Create a completed turn with configurable `web_search_enabled`. Returns the `request_id`.
async fn create_completed_turn_inner(
    db: &crate::domain::service::DbProvider,
    turn_repo: &impl TurnRepository,
    message_repo: &impl crate::domain::repos::MessageRepository,
    tenant_id: Uuid,
    chat_id: Uuid,
    user_id: Uuid,
    web_search_enabled: bool,
) -> Uuid {
    let request_id = Uuid::new_v4();
    let turn_id = Uuid::new_v4();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db.conn().unwrap();

    // Create turn
    turn_repo
        .create_turn(
            &conn,
            &scope,
            crate::domain::repos::CreateTurnParams {
                id: turn_id,
                tenant_id,
                chat_id,
                request_id,
                requester_type: "user".to_owned(),
                requester_user_id: Some(user_id),
                reserve_tokens: None,
                max_output_tokens_applied: None,
                reserved_credits_micro: None,
                policy_version_applied: None,
                effective_model: Some("gpt-5.2".to_owned()),
                minimal_generation_floor_applied: None,
                web_search_enabled,
            },
        )
        .await
        .unwrap();

    // Create user message
    message_repo
        .insert_user_message(
            &conn,
            &scope,
            crate::domain::repos::InsertUserMessageParams {
                id: Uuid::new_v4(),
                tenant_id,
                chat_id,
                request_id,
                content: "Hello world".to_owned(),
            },
        )
        .await
        .unwrap();

    // Create assistant message (required by FK on assistant_message_id)
    let assistant_msg_id = Uuid::new_v4();
    message_repo
        .insert_assistant_message(
            &conn,
            &scope,
            crate::domain::repos::InsertAssistantMessageParams {
                id: assistant_msg_id,
                tenant_id,
                chat_id,
                request_id,
                content: "Assistant reply".to_owned(),
                input_tokens: Some(10),
                output_tokens: Some(5),
                cache_read_input_tokens: None,
                cache_write_input_tokens: None,
                reasoning_tokens: None,
                model: Some("gpt-5.2".to_owned()),
                provider_response_id: None,
            },
        )
        .await
        .unwrap();

    // Transition to completed
    turn_repo
        .cas_update_state(
            &conn,
            &scope,
            crate::domain::repos::CasTerminalParams {
                turn_id,
                state: TurnState::Completed,
                error_code: None,
                error_detail: None,
                assistant_message_id: Some(assistant_msg_id),
                provider_response_id: None,
            },
        )
        .await
        .unwrap();

    request_id
}

// ════════════════════════════════════════════════════════════════════════════
// TurnService::get
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_returns_completed_turn() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let turn = svc.get(&ctx, chat_id, request_id).await.unwrap();
    assert_eq!(turn.request_id, request_id);
    assert_eq!(turn.chat_id, chat_id);
    assert_eq!(turn.state, TurnState::Completed);
    assert!(turn.assistant_message_id.is_some());
}

#[tokio::test]
async fn get_returns_running_turn() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = Uuid::new_v4();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    svc.turn_repo
        .create_turn(
            &conn,
            &scope,
            crate::domain::repos::CreateTurnParams {
                id: Uuid::new_v4(),
                tenant_id,
                chat_id,
                request_id,
                requester_type: "user".to_owned(),
                requester_user_id: Some(ctx.subject_id()),
                reserve_tokens: None,
                max_output_tokens_applied: None,
                reserved_credits_micro: None,
                policy_version_applied: None,
                effective_model: None,
                minimal_generation_floor_applied: None,
                web_search_enabled: false,
            },
        )
        .await
        .unwrap();

    let turn = svc.get(&ctx, chat_id, request_id).await.unwrap();
    assert_eq!(turn.request_id, request_id);
    assert_eq!(turn.state, TurnState::Running);
}

#[tokio::test]
async fn get_nonexistent_turn_returns_not_found() {
    let (svc, ctx, chat_id, _) = setup().await;

    let err = svc.get(&ctx, chat_id, Uuid::new_v4()).await.unwrap_err();
    assert!(
        matches!(err, MutationError::TurnNotFound { .. }),
        "expected TurnNotFound, got: {err:?}"
    );
}

#[tokio::test]
async fn get_nonexistent_chat_returns_chat_not_found() {
    let (svc, ctx, _, _) = setup().await;

    let err = svc
        .get(&ctx, Uuid::new_v4(), Uuid::new_v4())
        .await
        .unwrap_err();
    assert!(
        matches!(err, MutationError::ChatNotFound { .. }),
        "expected ChatNotFound, got: {err:?}"
    );
}

// ════════════════════════════════════════════════════════════════════════════
// 7.4: validate_mutation — 5 checks in order
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn delete_nonexistent_turn_returns_turn_not_found() {
    let (svc, ctx, chat_id, _) = setup().await;
    let fake_rid = Uuid::new_v4();

    let err = svc.delete(&ctx, chat_id, fake_rid).await.unwrap_err();
    assert!(
        matches!(err, MutationError::TurnNotFound { .. }),
        "expected TurnNotFound, got: {err:?}"
    );
}

#[tokio::test]
async fn delete_nonexistent_chat_returns_chat_not_found() {
    let (svc, ctx, _, _) = setup().await;
    let fake_chat = Uuid::new_v4();
    let fake_rid = Uuid::new_v4();

    let err = svc.delete(&ctx, fake_chat, fake_rid).await.unwrap_err();
    assert!(
        matches!(err, MutationError::ChatNotFound { .. }),
        "expected ChatNotFound, got: {err:?}"
    );
}

#[tokio::test]
async fn delete_wrong_owner_returns_forbidden() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    // Create a turn with a DIFFERENT requester_user_id than ctx.subject_id()
    let other_user_id = Uuid::new_v4();
    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        other_user_id,
    )
    .await;

    // ctx.subject_id() != other_user_id → ownership check fails
    let err = svc.delete(&ctx, chat_id, request_id).await.unwrap_err();
    assert!(
        matches!(err, MutationError::Forbidden),
        "expected Forbidden, got: {err:?}"
    );
}

#[tokio::test]
async fn delete_running_turn_returns_invalid_turn_state() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    // Create a running turn (don't transition to completed)
    let request_id = Uuid::new_v4();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    svc.turn_repo
        .create_turn(
            &conn,
            &scope,
            crate::domain::repos::CreateTurnParams {
                id: Uuid::new_v4(),
                tenant_id,
                chat_id,
                request_id,
                requester_type: "user".to_owned(),
                requester_user_id: Some(ctx.subject_id()),
                reserve_tokens: None,
                max_output_tokens_applied: None,
                reserved_credits_micro: None,
                policy_version_applied: None,
                effective_model: None,
                minimal_generation_floor_applied: None,
                web_search_enabled: false,
            },
        )
        .await
        .unwrap();

    let err = svc.delete(&ctx, chat_id, request_id).await.unwrap_err();
    assert!(
        matches!(
            err,
            MutationError::InvalidTurnState {
                state: TurnState::Running
            }
        ),
        "expected InvalidTurnState(Running), got: {err:?}"
    );
}

#[tokio::test]
async fn delete_non_latest_turn_returns_not_latest() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    // Create two completed turns
    let rid1 = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;
    // Small delay to ensure different started_at
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    let _rid2 = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    // Try to delete the FIRST turn (not the latest)
    let err = svc.delete(&ctx, chat_id, rid1).await.unwrap_err();
    assert!(
        matches!(err, MutationError::NotLatestTurn),
        "expected NotLatestTurn, got: {err:?}"
    );
}

// ════════════════════════════════════════════════════════════════════════════
// 7.1: TurnService::delete — success + edge cases
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn delete_success_soft_deletes_turn() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    svc.delete(&ctx, chat_id, request_id).await.unwrap();

    // Verify the turn is soft-deleted (deleted_at != NULL)
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap()
        .unwrap();
    assert!(turn.deleted_at.is_some());
    assert!(turn.replaced_by_request_id.is_none());
}

#[tokio::test]
async fn delete_already_deleted_turn_returns_not_latest() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    // Delete once
    svc.delete(&ctx, chat_id, request_id).await.unwrap();

    // Try to delete again — should fail (soft-deleted turns excluded from latest check)
    let err = svc.delete(&ctx, chat_id, request_id).await.unwrap_err();
    // After soft-delete, find_latest_for_update won't find the turn,
    // so the turn won't match the latest. The exact error depends on
    // whether there are other turns or not.
    assert!(
        matches!(
            err,
            MutationError::NotLatestTurn | MutationError::TurnNotFound { .. }
        ),
        "expected NotLatestTurn or TurnNotFound, got: {err:?}"
    );
}

// ════════════════════════════════════════════════════════════════════════════
// 7.1b: delete soft-deletes messages alongside turn
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn delete_soft_deletes_messages_alongside_turn() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    // Before delete: messages are visible
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let msgs_before = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap();
    assert_eq!(
        msgs_before.len(),
        2,
        "user + assistant messages should exist"
    );

    svc.delete(&ctx, chat_id, request_id).await.unwrap();

    // After delete: messages are hidden (find_by_chat_and_request_id filters deleted_at IS NULL)
    let msgs_after = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap();
    assert!(
        msgs_after.is_empty(),
        "messages should be soft-deleted after turn delete, got {} messages",
        msgs_after.len()
    );
}

// ════════════════════════════════════════════════════════════════════════════
// 7.2: TurnService::retry
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn retry_success_returns_new_request_id_and_content() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc.retry(&ctx, chat_id, request_id).await.unwrap();
    assert_ne!(result.new_request_id, request_id);
    assert_eq!(result.user_content, "Hello world");

    // Verify old turn is soft-deleted with replacement link
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let old_turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap()
        .unwrap();
    assert!(old_turn.deleted_at.is_some());
    assert_eq!(old_turn.replaced_by_request_id, Some(result.new_request_id));

    // Verify new turn exists in running state
    let new_turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, result.new_request_id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(new_turn.state, TurnState::Running);
}

#[tokio::test]
async fn retry_soft_deletes_old_messages_and_creates_new_user_message() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc.retry(&ctx, chat_id, request_id).await.unwrap();

    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();

    // Old messages should be soft-deleted
    let old_msgs = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap();
    assert!(
        old_msgs.is_empty(),
        "old turn messages should be soft-deleted after retry"
    );

    // New user message should exist under the new request_id
    let new_msgs = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, result.new_request_id)
        .await
        .unwrap();
    assert_eq!(
        new_msgs.len(),
        1,
        "retry should create exactly one new user message"
    );
    assert_eq!(new_msgs[0].content, "Hello world");
}

// ════════════════════════════════════════════════════════════════════════════
// 7.3: TurnService::edit
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn edit_success_returns_updated_content() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc
        .edit(&ctx, chat_id, request_id, "Updated content".to_owned())
        .await
        .unwrap();
    assert_ne!(result.new_request_id, request_id);
    assert_eq!(result.user_content, "Updated content");

    // Verify old turn soft-deleted with replacement
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let old_turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap()
        .unwrap();
    assert!(old_turn.deleted_at.is_some());
    assert_eq!(old_turn.replaced_by_request_id, Some(result.new_request_id));
}

#[tokio::test]
async fn edit_soft_deletes_old_messages_and_creates_new_user_message() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc
        .edit(&ctx, chat_id, request_id, "Edited content".to_owned())
        .await
        .unwrap();

    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();

    // Old messages should be soft-deleted
    let old_msgs = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, request_id)
        .await
        .unwrap();
    assert!(
        old_msgs.is_empty(),
        "old turn messages should be soft-deleted after edit"
    );

    // New user message should exist with edited content
    let new_msgs = svc
        .message_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, result.new_request_id)
        .await
        .unwrap();
    assert_eq!(
        new_msgs.len(),
        1,
        "edit should create exactly one new user message"
    );
    assert_eq!(new_msgs[0].content, "Edited content");
}

#[tokio::test]
async fn edit_uses_same_validation_as_retry() {
    let (svc, ctx, chat_id, _) = setup().await;

    // Non-existent turn
    let err = svc
        .edit(&ctx, chat_id, Uuid::new_v4(), "new".to_owned())
        .await
        .unwrap_err();
    assert!(matches!(err, MutationError::TurnNotFound { .. }));
}

// ════════════════════════════════════════════════════════════════════════════
// Metrics emission
// ════════════════════════════════════════════════════════════════════════════

/// Successful delete emits `turn_mutation` counter + latency histogram.
#[tokio::test]
async fn delete_success_emits_metrics() {
    let db = inmem_db().await;
    let db = mock_db_provider(db);
    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let chat_repo = Arc::new(repo::chat_repo::ChatRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));
    let turn_repo = Arc::new(repo::turn_repo::TurnRepository);
    let message_repo = Arc::new(repo::message_repo::MessageRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));

    let chat_id = Uuid::now_v7();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db.conn().unwrap();
    chat_repo
        .create(
            &conn,
            &scope,
            crate::domain::models::Chat {
                id: chat_id,
                tenant_id,
                user_id: ctx.subject_id(),
                model: "gpt-5.2".to_owned(),
                title: Some("Test chat".to_owned()),
                is_temporary: false,
                created_at: time::OffsetDateTime::now_utc(),
                updated_at: time::OffsetDateTime::now_utc(),
            },
        )
        .await
        .unwrap();

    let metrics = Arc::new(TestMetrics::new());
    let svc = TurnService::new(
        Arc::clone(&db),
        turn_repo,
        message_repo,
        chat_repo,
        Arc::new(crate::infra::db::repo::message_attachment_repo::MessageAttachmentRepository),
        mock_enforcer(),
        Arc::new(RecordingOutboxEnqueuer::new()),
        Arc::clone(&metrics) as _,
    );

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    svc.delete(&ctx, chat_id, request_id).await.unwrap();

    assert_eq!(
        metrics.turn_mutation.load(Ordering::Relaxed),
        1,
        "should record turn_mutation counter"
    );
    assert_eq!(
        metrics.turn_mutation_latency_ms.load(Ordering::Relaxed),
        1,
        "should record turn_mutation_latency_ms histogram"
    );
}

// ════════════════════════════════════════════════════════════════════════════
// Audit event emission
// ════════════════════════════════════════════════════════════════════════════

/// Setup identical to `setup()` but with a [`RecordingOutboxEnqueuer`] so we
/// can assert on enqueued audit events synchronously — no flush needed.
async fn setup_with_audit() -> (
    TurnService<
        repo::turn_repo::TurnRepository,
        repo::message_repo::MessageRepository,
        repo::chat_repo::ChatRepository,
        repo::message_attachment_repo::MessageAttachmentRepository,
    >,
    modkit_security::SecurityContext,
    Uuid, // chat_id
    Uuid, // tenant_id
    Arc<RecordingOutboxEnqueuer>,
) {
    let db = inmem_db().await;
    let db = mock_db_provider(db);
    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let chat_repo = Arc::new(repo::chat_repo::ChatRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));
    let turn_repo = Arc::new(repo::turn_repo::TurnRepository);
    let message_repo = Arc::new(repo::message_repo::MessageRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));

    let chat_id = Uuid::now_v7();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db.conn().unwrap();
    chat_repo
        .create(
            &conn,
            &scope,
            crate::domain::models::Chat {
                id: chat_id,
                tenant_id,
                user_id: ctx.subject_id(),
                model: "gpt-5.2".to_owned(),
                title: Some("Test chat".to_owned()),
                is_temporary: false,
                created_at: time::OffsetDateTime::now_utc(),
                updated_at: time::OffsetDateTime::now_utc(),
            },
        )
        .await
        .unwrap();

    let outbox = Arc::new(RecordingOutboxEnqueuer::new());
    let svc = TurnService::new(
        Arc::clone(&db),
        turn_repo,
        message_repo,
        chat_repo,
        Arc::new(crate::infra::db::repo::message_attachment_repo::MessageAttachmentRepository),
        mock_enforcer(),
        Arc::clone(&outbox) as Arc<dyn crate::domain::repos::OutboxEnqueuer>,
        Arc::new(crate::domain::ports::metrics::NoopMetrics),
    );

    (svc, ctx, chat_id, tenant_id, outbox)
}

#[tokio::test]
async fn delete_emits_turn_delete_audit_event() {
    let (svc, ctx, chat_id, tenant_id, outbox) = setup_with_audit().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    svc.delete(&ctx, chat_id, request_id).await.unwrap();

    let captured = outbox.audit_events();
    assert_eq!(captured.len(), 1, "expected exactly 1 audit event");
    match &captured[0] {
        AuditEnvelope::Delete(evt) => {
            assert_eq!(evt.tenant_id, tenant_id);
            assert_eq!(evt.actor_user_id, ctx.subject_id());
            assert_eq!(evt.chat_id, chat_id);
            assert_eq!(evt.request_id, request_id);
        }
        other => panic!("expected Delete event, got: {other:?}"),
    }
}

#[tokio::test]
async fn delete_failure_does_not_emit_audit_event() {
    let (svc, ctx, chat_id, _, outbox) = setup_with_audit().await;

    // Non-existent turn → transaction rolls back, audit event not enqueued.
    svc.delete(&ctx, chat_id, Uuid::new_v4()).await.unwrap_err();

    assert!(
        outbox.audit_events().is_empty(),
        "no audit event should be enqueued on failure"
    );
}

#[tokio::test]
async fn retry_emits_turn_retry_audit_event() {
    let (svc, ctx, chat_id, tenant_id, outbox) = setup_with_audit().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc.retry(&ctx, chat_id, request_id).await.unwrap();

    let captured = outbox.audit_events();
    assert_eq!(captured.len(), 1, "expected exactly 1 audit event");
    match &captured[0] {
        AuditEnvelope::Mutation(evt) => {
            assert_eq!(evt.tenant_id, tenant_id);
            assert_eq!(evt.actor_user_id, ctx.subject_id());
            assert_eq!(evt.chat_id, chat_id);
            assert_eq!(evt.original_request_id, request_id);
            assert_eq!(evt.new_request_id, result.new_request_id);
            assert_eq!(
                evt.event_type,
                mini_chat_sdk::TurnMutationAuditEventType::TurnRetry
            );
        }
        other => panic!("expected Mutation(Retry) event, got: {other:?}"),
    }
}

#[tokio::test]
async fn retry_failure_does_not_emit_audit_event() {
    let (svc, ctx, chat_id, _, outbox) = setup_with_audit().await;

    svc.retry(&ctx, chat_id, Uuid::new_v4()).await.unwrap_err();

    assert!(
        outbox.audit_events().is_empty(),
        "no audit event should be enqueued on failure"
    );
}

#[tokio::test]
async fn edit_emits_turn_edit_audit_event() {
    let (svc, ctx, chat_id, tenant_id, outbox) = setup_with_audit().await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
    )
    .await;

    let result = svc
        .edit(&ctx, chat_id, request_id, "Edited text".to_owned())
        .await
        .unwrap();

    let captured = outbox.audit_events();
    assert_eq!(captured.len(), 1, "expected exactly 1 audit event");
    match &captured[0] {
        AuditEnvelope::Mutation(evt) => {
            assert_eq!(evt.tenant_id, tenant_id);
            assert_eq!(evt.actor_user_id, ctx.subject_id());
            assert_eq!(evt.chat_id, chat_id);
            assert_eq!(evt.original_request_id, request_id);
            assert_eq!(evt.new_request_id, result.new_request_id);
            assert_eq!(
                evt.event_type,
                mini_chat_sdk::TurnMutationAuditEventType::TurnEdit
            );
        }
        other => panic!("expected Mutation(Edit) event, got: {other:?}"),
    }
}

#[tokio::test]
async fn edit_failure_does_not_emit_audit_event() {
    let (svc, ctx, chat_id, _, outbox) = setup_with_audit().await;

    svc.edit(&ctx, chat_id, Uuid::new_v4(), "new".to_owned())
        .await
        .unwrap_err();

    assert!(
        outbox.audit_events().is_empty(),
        "no audit event should be enqueued on failure"
    );
}

// ── Tenant-only AuthZ: user isolation via ensure_owner ──

/// Build a `TurnService` with tenant-only enforcer for cross-owner tests.
/// Creates a chat owned by `chat_owner_id` and returns the service, `tenant_id`, and `chat_id`.
async fn setup_tenant_only_authz(
    chat_owner_id: Uuid,
) -> (
    TurnService<
        repo::turn_repo::TurnRepository,
        repo::message_repo::MessageRepository,
        repo::chat_repo::ChatRepository,
        repo::message_attachment_repo::MessageAttachmentRepository,
    >,
    Uuid, // tenant_id
    Uuid, // chat_id
) {
    let db = inmem_db().await;
    let db = mock_db_provider(db);
    let tenant_id = Uuid::new_v4();

    let chat_repo = Arc::new(repo::chat_repo::ChatRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));
    let turn_repo = Arc::new(repo::turn_repo::TurnRepository);
    let message_repo = Arc::new(repo::message_repo::MessageRepository::new(
        modkit_db::odata::LimitCfg {
            default: 20,
            max: 100,
        },
    ));

    let chat_id = Uuid::now_v7();
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db.conn().unwrap();
    chat_repo
        .create(
            &conn,
            &scope,
            crate::domain::models::Chat {
                id: chat_id,
                tenant_id,
                user_id: chat_owner_id,
                model: "gpt-5.2".to_owned(),
                title: Some("Test chat".to_owned()),
                is_temporary: false,
                created_at: time::OffsetDateTime::now_utc(),
                updated_at: time::OffsetDateTime::now_utc(),
            },
        )
        .await
        .unwrap();

    let svc = TurnService::new(
        Arc::clone(&db),
        turn_repo,
        message_repo,
        chat_repo,
        Arc::new(crate::infra::db::repo::message_attachment_repo::MessageAttachmentRepository),
        mock_tenant_only_enforcer(),
        Arc::new(RecordingOutboxEnqueuer::new()),
        Arc::new(crate::domain::ports::metrics::NoopMetrics),
    );

    (svc, tenant_id, chat_id)
}

#[tokio::test]
async fn get_turn_tenant_only_authz_cross_owner_not_found() {
    let user_a = Uuid::new_v4();
    let user_b = Uuid::new_v4();

    let (svc, tenant_id, chat_id) = setup_tenant_only_authz(user_a).await;

    let request_id = create_completed_turn(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        user_a,
    )
    .await;

    // User B (same tenant) tries to read the turn — must fail
    let ctx_b = test_security_ctx_with_id(tenant_id, user_b);
    let err = svc.get(&ctx_b, chat_id, request_id).await.unwrap_err();
    assert!(
        matches!(err, MutationError::ChatNotFound { .. }),
        "Cross-owner get must fail with ChatNotFound, got: {err:?}"
    );
}

// ════════════════════════════════════════════════════════════════════════════
// web_search_enabled preservation through retry/edit
// ════════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn retry_preserves_web_search_enabled() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn_inner(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
        true,
    )
    .await;

    let result = svc.retry(&ctx, chat_id, request_id).await.unwrap();

    // MutationResult must carry the flag
    assert!(
        result.web_search_enabled,
        "retry MutationResult must preserve web_search_enabled=true"
    );

    // New turn in DB must also have the flag
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let new_turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, result.new_request_id)
        .await
        .unwrap()
        .unwrap();
    assert!(
        new_turn.web_search_enabled,
        "new turn created by retry must have web_search_enabled=true"
    );
}

#[tokio::test]
async fn edit_preserves_web_search_enabled() {
    let (svc, ctx, chat_id, tenant_id) = setup().await;

    let request_id = create_completed_turn_inner(
        &svc.db,
        &*svc.turn_repo,
        &*svc.message_repo,
        tenant_id,
        chat_id,
        ctx.subject_id(),
        true,
    )
    .await;

    let result = svc
        .edit(&ctx, chat_id, request_id, "updated content".to_owned())
        .await
        .unwrap();

    // MutationResult must carry the flag
    assert!(
        result.web_search_enabled,
        "edit MutationResult must preserve web_search_enabled=true"
    );

    // New turn in DB must also have the flag
    let scope = AccessScope::for_tenant(tenant_id);
    let conn = svc.db.conn().unwrap();
    let new_turn = svc
        .turn_repo
        .find_by_chat_and_request_id(&conn, &scope, chat_id, result.new_request_id)
        .await
        .unwrap()
        .unwrap();
    assert!(
        new_turn.web_search_enabled,
        "new turn created by edit must have web_search_enabled=true"
    );
    assert_eq!(result.user_content, "updated content");
}