cf-mini-chat 0.1.28

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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
use std::collections::HashMap;
use std::sync::Arc;

use bytes::Bytes;
use uuid::Uuid;

use crate::config::{ProviderEntry, RagConfig, StorageKind};
use crate::domain::repos::VectorStoreRepository as VectorStoreRepoTrait;
use crate::domain::service::test_helpers::{
    MockModelResolver, MockOagwGateway, NoopOutboxEnqueuer, RecordingOutboxEnqueuer,
    TestCatalogEntryParams, bytes_to_stream, inmem_db, insert_chat_for_user,
    insert_chat_with_model, insert_test_message, mock_db_provider, mock_model_resolver,
    mock_tenant_only_enforcer, test_catalog_entry,
};
use crate::infra::db::repo::{
    chat_repo::ChatRepository as OrmChatRepository,
    vector_store_repo::VectorStoreRepository as OrmVectorStoreRepository,
};
use crate::infra::llm::provider_resolver::ProviderResolver;
use crate::infra::llm::providers::ProviderKind;

use super::AttachmentService;

use crate::infra::db::repo::attachment_repo::AttachmentRepository as OrmAttachmentRepository;

type TestAttachmentService =
    AttachmentService<OrmChatRepository, OrmAttachmentRepository, OrmVectorStoreRepository>;

/// Build a `ProviderResolver` with a single `"openai"` provider for tests.
///
/// `upstream_alias_for("openai", None)` → `Some("test-host")`
/// `resolve_storage_backend("openai")` → `"openai"`
fn test_provider_resolver(
    oagw: &Arc<dyn oagw_sdk::ServiceGatewayClientV1>,
) -> Arc<ProviderResolver> {
    let mut providers = HashMap::new();
    providers.insert(
        "openai".to_owned(),
        ProviderEntry {
            kind: ProviderKind::OpenAiResponses,
            upstream_alias: Some("test-host".to_owned()),
            host: "test-host".to_owned(),
            port: None,
            use_http: false,
            api_path: "/v1/responses".to_owned(),
            auth_plugin_type: None,
            auth_config: None,
            storage_backend: None,
            supports_file_search_filters: true,
            storage_kind: StorageKind::OpenAi,
            api_version: None,
            tenant_overrides: HashMap::new(),
        },
    );
    Arc::new(ProviderResolver::new(oagw, providers))
}

/// Build an `AttachmentService` wired to real repos + in-memory DB.
fn build_service(
    db: modkit_db::Db,
    oagw: Arc<dyn oagw_sdk::ServiceGatewayClientV1>,
    outbox: Arc<dyn crate::domain::repos::OutboxEnqueuer>,
    rag_config: RagConfig,
) -> TestAttachmentService {
    let db = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(modkit_db::odata::LimitCfg {
        default: 20,
        max: 100,
    }));
    let attachment_repo = Arc::new(OrmAttachmentRepository);
    let vector_store_repo = Arc::new(OrmVectorStoreRepository);
    let provider_resolver = test_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client =
        Arc::new(crate::infra::llm::providers::rag_http_client::RagHttpClient::new(oagw));
    let file_storage: Arc<dyn crate::domain::ports::FileStorageProvider> = Arc::new(
        crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
            Arc::clone(&rag_client),
            Arc::clone(&provider_resolver),
        ),
    );
    let vector_store_prov: Arc<dyn crate::domain::ports::VectorStoreProvider> = Arc::new(
        crate::infra::llm::providers::openai_vector_store::OpenAiVectorStore::new(
            rag_client,
            Arc::clone(&provider_resolver),
        ),
    );

    AttachmentService::new(
        db,
        attachment_repo,
        chat_repo,
        vector_store_repo,
        outbox,
        mock_tenant_only_enforcer(),
        file_storage,
        vector_store_prov,
        provider_resolver,
        mock_model_resolver(),
        rag_config,
        crate::config::ThumbnailConfig::default(),
        Arc::new(crate::domain::ports::metrics::NoopMetrics),
    )
}

/// Build an `AttachmentService` with a custom metrics implementation.
fn build_service_with_metrics(
    db: modkit_db::Db,
    oagw: Arc<dyn oagw_sdk::ServiceGatewayClientV1>,
    outbox: Arc<dyn crate::domain::repos::OutboxEnqueuer>,
    rag_config: RagConfig,
    metrics: Arc<dyn crate::domain::ports::MiniChatMetricsPort>,
) -> TestAttachmentService {
    let db = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(modkit_db::odata::LimitCfg {
        default: 20,
        max: 100,
    }));
    let attachment_repo = Arc::new(OrmAttachmentRepository);
    let vector_store_repo = Arc::new(OrmVectorStoreRepository);
    let provider_resolver = test_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client =
        Arc::new(crate::infra::llm::providers::rag_http_client::RagHttpClient::new(oagw));
    let file_storage: Arc<dyn crate::domain::ports::FileStorageProvider> = Arc::new(
        crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
            Arc::clone(&rag_client),
            Arc::clone(&provider_resolver),
        ),
    );
    let vector_store_prov: Arc<dyn crate::domain::ports::VectorStoreProvider> = Arc::new(
        crate::infra::llm::providers::openai_vector_store::OpenAiVectorStore::new(
            rag_client,
            Arc::clone(&provider_resolver),
        ),
    );

    AttachmentService::new(
        db,
        attachment_repo,
        chat_repo,
        vector_store_repo,
        outbox,
        mock_tenant_only_enforcer(),
        file_storage,
        vector_store_prov,
        provider_resolver,
        mock_model_resolver(),
        rag_config,
        crate::config::ThumbnailConfig::default(),
        metrics,
    )
}

/// Helper: JSON response for a successful file upload.
fn file_upload_response(file_id: &str) -> serde_json::Value {
    serde_json::json!({ "id": file_id })
}

/// Helper: JSON response for vector store creation.
fn vector_store_create_response(vs_id: &str) -> serde_json::Value {
    serde_json::json!({ "id": vs_id })
}

/// Helper: JSON response for adding a file to a vector store.
fn vector_store_add_file_response() -> serde_json::Value {
    serde_json::json!({ "id": "vsf-abc123", "status": "in_progress" })
}

/// Test helper: wraps the new streaming `upload_file` with the old simple interface.
///
/// Calls `get_upload_context`, validates MIME, converts bytes to stream, and
/// calls `upload_file` with the given `size_hint`.
async fn test_upload_file_inner(
    svc: &TestAttachmentService,
    ctx: &modkit_security::SecurityContext,
    chat_id: Uuid,
    filename: &str,
    content_type: &str,
    data: Bytes,
    size_hint: Option<u64>,
) -> Result<crate::infra::db::entity::attachment::Model, crate::domain::error::DomainError> {
    use crate::domain::mime_validation::{
        infer_mime_from_extension, normalize_mime, remap_csv_to_plain, validate_mime,
    };
    // Resolve upload context (authz + limits)
    let upload_ctx = svc.get_upload_context(ctx, chat_id).await?;

    // MIME validation (mirrors what the handler does)
    let effective_ct = if normalize_mime(content_type) == "application/octet-stream" {
        infer_mime_from_extension(filename).unwrap_or(content_type)
    } else {
        content_type
    };
    let effective_ct = if upload_ctx.allow_csv_upload {
        remap_csv_to_plain(effective_ct).unwrap_or(effective_ct)
    } else {
        effective_ct
    };
    let validated = validate_mime(effective_ct)?;

    let stream = bytes_to_stream(data);

    svc.upload_file(
        ctx,
        chat_id,
        upload_ctx,
        filename.to_owned(),
        validated.mime,
        validated.kind,
        stream,
        size_hint,
    )
    .await
}

/// Upload with known `Content-Length`.
async fn test_upload_file(
    svc: &TestAttachmentService,
    ctx: &modkit_security::SecurityContext,
    chat_id: Uuid,
    filename: &str,
    content_type: &str,
    data: Bytes,
) -> Result<crate::infra::db::entity::attachment::Model, crate::domain::error::DomainError> {
    let size = data.len() as u64;
    test_upload_file_inner(svc, ctx, chat_id, filename, content_type, data, Some(size)).await
}

/// Upload without `Content-Length` (simulates chunked transfer encoding).
async fn test_upload_file_chunked(
    svc: &TestAttachmentService,
    ctx: &modkit_security::SecurityContext,
    chat_id: Uuid,
    filename: &str,
    content_type: &str,
    data: Bytes,
) -> Result<crate::infra::db::entity::attachment::Model, crate::domain::error::DomainError> {
    test_upload_file_inner(svc, ctx, chat_id, filename, content_type, data, None).await
}

// ── P5-B1: Upload document full lifecycle ──

#[tokio::test]
async fn test_upload_document_full_lifecycle() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Queue 3 OAGW responses: file upload → vector store create → add file to VS
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-uploaded-001")),
        Ok(vector_store_create_response("vs-new-001")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "report.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 1024]),
    )
    .await;

    assert!(result.is_ok(), "upload_file failed: {result:?}");
    let attachment = result.unwrap();

    // Verify final state
    assert_eq!(attachment.chat_id, chat_id);
    assert_eq!(attachment.tenant_id, tenant_id);
    assert_eq!(attachment.uploaded_by_user_id, user_id);
    assert_eq!(attachment.filename, "report.pdf");
    assert_eq!(attachment.content_type, "application/pdf");
    assert_eq!(attachment.size_bytes, 1024);
    assert_eq!(attachment.storage_backend, "openai");
    assert_eq!(
        attachment.provider_file_id.as_deref(),
        Some("file-uploaded-001")
    );
    assert_eq!(
        attachment.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Ready,
    );
    assert!(attachment.deleted_at.is_none());

    // Verify OAGW calls
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 3, "expected 3 OAGW calls");

    // 1st call: file upload
    assert!(
        requests[0].uri.contains("/v1/files"),
        "1st call should be file upload, got: {}",
        requests[0].uri
    );

    // 2nd call: vector store creation
    assert!(
        requests[1].uri.contains("/v1/vector_stores"),
        "2nd call should be vector store create, got: {}",
        requests[1].uri
    );

    // 3rd call: add file to vector store
    assert!(
        requests[2]
            .uri
            .contains("/v1/vector_stores/vs-new-001/files"),
        "3rd call should be add-file-to-VS, got: {}",
        requests[2].uri
    );

    // Verify attachment_id attribute in the add-file request body
    let add_file_body: serde_json::Value =
        serde_json::from_str(&requests[2].body).expect("add-file body should be JSON");
    assert_eq!(
        add_file_body["file_id"], "file-uploaded-001",
        "add-file should reference the uploaded file"
    );
    assert_eq!(
        add_file_body["attributes"]["attachment_id"],
        attachment.id.to_string(),
        "add-file should tag with attachment_id"
    );
}

// ── P5-B2: Upload image lifecycle (skips vector store) ──

#[tokio::test]
async fn test_upload_image_skips_vector_store() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Only 1 OAGW response needed: file upload (no vector store for images)
    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-img-001"))]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "photo.png",
        "image/png",
        Bytes::from(vec![0u8; 2048]),
    )
    .await;

    assert!(result.is_ok(), "upload image failed: {result:?}");
    let attachment = result.unwrap();

    assert_eq!(
        attachment.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Ready,
    );
    assert_eq!(attachment.content_type, "image/png");
    assert_eq!(attachment.provider_file_id.as_deref(), Some("file-img-001"));

    // Only 1 OAGW call (file upload, no vector store)
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(
        requests.len(),
        1,
        "image upload should make only 1 OAGW call"
    );
    assert!(requests[0].uri.contains("/v1/files"));
}

// ── P5-B3: Second upload reuses existing vector store ──

#[tokio::test]
async fn test_second_upload_reuses_vector_store() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // First upload: file upload + VS create + add file = 3 calls
    // Second upload: file upload + add file = 2 calls (VS already exists)
    let oagw = MockOagwGateway::with_responses(vec![
        // 1st upload
        Ok(file_upload_response("file-001")),
        Ok(vector_store_create_response("vs-reuse-001")),
        Ok(vector_store_add_file_response()),
        // 2nd upload
        Ok(file_upload_response("file-002")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    // First upload
    let r1 = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "a.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;
    assert!(r1.is_ok(), "1st upload failed: {r1:?}");

    // Second upload — should reuse existing vector store
    let r2 = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "b.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;
    assert!(r2.is_ok(), "2nd upload failed: {r2:?}");

    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 5, "expected 3 + 2 = 5 OAGW calls");

    // The 4th call should be file upload (not vector store create)
    assert!(
        requests[3].uri.contains("/v1/files"),
        "4th call should be file upload, got: {}",
        requests[3].uri
    );
    // The 5th call should add file to the EXISTING vector store
    assert!(
        requests[4]
            .uri
            .contains("/v1/vector_stores/vs-reuse-001/files"),
        "5th call should reuse VS, got: {}",
        requests[4].uri
    );
}

// ── P5-C1: Unsupported MIME type rejected ──

#[tokio::test]
async fn test_upload_unsupported_mime_rejected() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]); // no calls expected
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "video.mp4",
        "video/mp4",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err());
    let requests = oagw.captured_requests.lock().unwrap();
    assert!(requests.is_empty(), "no OAGW calls for rejected MIME");
}

// ── P5-C2: Chat not found ──

#[tokio::test]
async fn test_upload_chat_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let nonexistent_chat = Uuid::new_v4();
    // Don't insert any chat

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        nonexistent_chat,
        "doc.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "upload to nonexistent chat should fail");
}

// ── P5-C3: Document limit exceeded ──

#[tokio::test]
async fn test_upload_document_limit_exceeded() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Pre-fill chat with max documents
    let config = RagConfig {
        max_documents_per_chat: 2,
        max_total_upload_mb_per_chat: 100,
        ..RagConfig::default()
    };

    // Insert 2 existing document attachments (at limit)
    for _ in 0..2 {
        let mut params =
            crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
                tenant_id, chat_id,
            );
        params.uploaded_by_user_id = user_id;
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;
    }

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, config);

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "third.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(
            err,
            crate::domain::error::DomainError::DocumentLimitExceeded { .. }
        ),
        "expected DocumentLimitExceeded, got: {err:?}"
    );
}

// ── P5-C4: Storage limit exceeded ──

#[tokio::test]
async fn test_upload_storage_limit_exceeded() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let config = RagConfig {
        max_documents_per_chat: 50,
        max_total_upload_mb_per_chat: 1, // 1 MB limit
        ..RagConfig::default()
    };

    // Insert a large existing attachment (close to limit)
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.size_bytes = 900_000; // ~0.86 MB
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, config);

    // Try to upload another 200KB — would exceed 1 MB
    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "big.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 200_000]),
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(
            err,
            crate::domain::error::DomainError::StorageLimitExceeded { .. }
        ),
        "expected StorageLimitExceeded, got: {err:?}"
    );
}

// ── P5-C5: Post-upload storage limit for chunked uploads (no Content-Length) ──

#[tokio::test]
async fn test_upload_storage_limit_exceeded_chunked() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let config = RagConfig {
        max_documents_per_chat: 50,
        max_total_upload_mb_per_chat: 1, // 1 MB limit
        ..RagConfig::default()
    };

    // Insert a large existing attachment (close to limit)
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.size_bytes = 900_000; // ~0.86 MB
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // OAGW returns file upload success (the provider accepts the file)
    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-chunked-001"))]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, config);

    // Upload 200KB via chunked encoding (no Content-Length → size_hint = None).
    // The preflight check is skipped, but the post-upload check should reject.
    let result = test_upload_file_chunked(
        &svc,
        &ctx,
        chat_id,
        "big.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 200_000]),
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(
            err,
            crate::domain::error::DomainError::StorageLimitExceeded { .. }
        ),
        "expected StorageLimitExceeded for chunked upload, got: {err:?}"
    );
}

// ── P5-D1: Provider upload failure sets attachment to failed ──

#[tokio::test]
async fn test_upload_provider_failure_sets_failed() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // OAGW returns error on file upload
    let oagw =
        MockOagwGateway::single_error(oagw_sdk::error::ServiceGatewayError::ConnectionTimeout {
            detail: "mock timeout".to_owned(),
            instance: String::new(),
        });

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "fail.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "upload should fail when provider errors");
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::ProviderError { .. }
        ),
        "expected ProviderError"
    );
}

// ── P5-B4: Get attachment returns uploaded attachment ──

#[tokio::test]
async fn test_get_attachment_returns_uploaded() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a ready attachment
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.get_attachment(&ctx, chat_id, att_id).await;
    assert!(result.is_ok(), "get_attachment failed: {result:?}");
    let att = result.unwrap();
    assert_eq!(att.id, att_id);
    assert_eq!(att.filename, "test.pdf");
}

// ── P5-B5: Get attachment returns 404 for soft-deleted ──

#[tokio::test]
async fn test_get_attachment_soft_deleted_returns_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a soft-deleted attachment
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.deleted_at = Some(time::OffsetDateTime::now_utc());
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.get_attachment(&ctx, chat_id, att_id).await;
    assert!(result.is_err(), "soft-deleted should return error");
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "expected NotFound"
    );
}

// ── P5-F1: Delete attachment enqueues cleanup ──

#[tokio::test]
async fn test_delete_attachment_enqueues_cleanup() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(RecordingOutboxEnqueuer::new());
    let outbox_ref = Arc::clone(&outbox);
    let svc = build_service(
        db,
        Arc::clone(&oagw) as _,
        outbox as _,
        RagConfig::default(),
    );

    let result = svc.delete_attachment(&ctx, chat_id, att_id).await;
    assert!(result.is_ok(), "delete_attachment failed: {result:?}");

    // Verify cleanup event was enqueued
    let events = outbox_ref.cleanup_events.lock().unwrap();
    assert_eq!(events.len(), 1, "should enqueue 1 cleanup event");
    assert_eq!(events[0].attachment_id, att_id);
    assert_eq!(events[0].event_type, "attachment_deleted");
}

// ── P5-F2: Delete idempotent for already-deleted ──

#[tokio::test]
async fn test_delete_attachment_idempotent_already_deleted() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.deleted_at = Some(time::OffsetDateTime::now_utc());
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    // Should succeed (idempotent 204)
    let result = svc.delete_attachment(&ctx, chat_id, att_id).await;
    assert!(result.is_ok(), "idempotent delete should succeed");
}

// ── P5-F3: Delete by wrong user masked as not-found ──

#[tokio::test]
async fn test_delete_attachment_wrong_user_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let owner_id = Uuid::new_v4();
    let other_user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, owner_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = owner_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    // Different user tries to delete — chat ownership check rejects first
    // (more secure: user doesn't even learn the chat exists).
    let ctx =
        crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, other_user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.delete_attachment(&ctx, chat_id, att_id).await;
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "cross-owner delete must be masked as NotFound"
    );
}

// ── Cross-owner isolation (tenant-only authz, ensure_owner defence-in-depth) ──

#[tokio::test]
async fn test_get_attachment_cross_owner_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let owner_id = Uuid::new_v4();
    let other_user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, owner_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = owner_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    // Different user (same tenant) tries to read the attachment
    let ctx =
        crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, other_user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.get_attachment(&ctx, chat_id, att_id).await;
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "cross-owner get_attachment must be masked as NotFound"
    );
}

#[tokio::test]
async fn test_upload_attachment_cross_owner_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let owner_id = Uuid::new_v4();
    let other_user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, owner_id).await;

    // Different user (same tenant) tries to upload to owner's chat
    let ctx =
        crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, other_user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "test.pdf",
        "application/pdf",
        Bytes::from_static(b"dummy content"),
    )
    .await;
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "cross-owner upload must be masked as NotFound"
    );
    assert!(
        oagw.captured_requests.lock().unwrap().is_empty(),
        "cross-owner upload must fail before any provider call"
    );
}

// ── P5-C6: MIME charset stripped ──

#[tokio::test]
async fn test_upload_mime_charset_stripped() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // text/plain documents go through the full upload + VS flow
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-txt-001")),
        Ok(vector_store_create_response("vs-txt-001")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "notes.txt",
        "text/plain; charset=utf-8", // charset should be stripped
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(
        result.is_ok(),
        "upload with charset param failed: {result:?}"
    );
    let attachment = result.unwrap();

    // Stored MIME should have charset stripped
    assert_eq!(attachment.content_type, "text/plain");
    assert_eq!(
        attachment.attachment_kind,
        crate::infra::db::entity::attachment::AttachmentKind::Document
    );
}

// ── P5-D2: Vector store indexing failure ──

#[tokio::test]
async fn test_upload_vector_store_indexing_fails() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // File upload succeeds, VS create succeeds, add-file-to-VS fails
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-idx-fail")),
        Ok(vector_store_create_response("vs-idx-fail")),
        Err(oagw_sdk::error::ServiceGatewayError::ConnectionTimeout {
            detail: "indexing timeout".to_owned(),
            instance: String::new(),
        }),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "big_doc.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "indexing failure should propagate");
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::ProviderError { .. }
        ),
        "expected ProviderError for indexing failure"
    );

    // Verify: file upload + VS create + add-file attempted = 3 calls
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 3, "should have attempted all 3 OAGW calls");

    // Best-effort delete is fire-and-forget (spawned task), so we can't
    // deterministically assert it here — but the 3 captured calls confirm the
    // flow reached the add-file stage before failing.
}

// ── REAL-2: create_vector_store failure cleans up placeholder row ──

#[tokio::test]
async fn test_create_vector_store_failure_cleans_up_placeholder_row() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // File upload succeeds, then VS create fails (2nd OAGW call)
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-vs-fail")),
        Err(oagw_sdk::error::ServiceGatewayError::ConnectionTimeout {
            detail: "VS create timeout".to_owned(),
            instance: String::new(),
        }),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(
        db.clone(),
        Arc::clone(&oagw) as _,
        outbox,
        RagConfig::default(),
    );

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "test.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "VS create failure should propagate");

    // Allow async cleanup to run
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Verify: placeholder vector store row was cleaned up
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let vs_row = OrmVectorStoreRepository
        .find_by_chat(&conn, &scope, chat_id)
        .await
        .unwrap();
    assert!(
        vs_row.is_none(),
        "placeholder row should have been cleaned up after create_vector_store failure"
    );
}

// ── REAL-3: get_or_create_vector_store failure sets attachment to failed ──

#[tokio::test]
async fn test_vector_store_failure_sets_attachment_failed() {
    use crate::domain::repos::AttachmentRepository as _;
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // File upload succeeds (1st), VS create fails (2nd), file delete succeeds (3rd — spawned cleanup)
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-vs-fail-2")),
        Err(oagw_sdk::error::ServiceGatewayError::ConnectionTimeout {
            detail: "VS create timeout".to_owned(),
            instance: String::new(),
        }),
        Ok(serde_json::json!({"deleted": true})), // fire-and-forget file delete
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(
        db.clone(),
        Arc::clone(&oagw) as _,
        outbox,
        RagConfig::default(),
    );

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "report.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "VS create failure should propagate");

    // Allow async cleanup (spawn_delete_file) to run
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Verify attachment was set to failed with error_code = "vector_store_failed"
    // We can't get the attachment_id directly (generated inside upload_file), so
    // check that count_ready_documents returns 0 (no ready docs after failure).
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let repo = OrmAttachmentRepository;
    let ready_count: i64 = repo
        .count_ready_documents(&conn, &scope, chat_id)
        .await
        .unwrap();
    assert_eq!(ready_count, 0, "no ready docs expected after VS failure");
}

// ── P5-D3: Concurrent delete during upload (CAS set_uploaded returns 0) ──

#[tokio::test]
async fn test_upload_concurrent_delete_during_upload() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // File upload succeeds (OAGW returns file ID), but after that
    // we'll soft-delete the pending row before CAS set_uploaded runs.
    // This requires manual row insertion + soft-delete to simulate the race.
    //
    // However, with the integration approach, the upload_file method does
    // everything sequentially. To test the CAS=0 path, we'd need to
    // intercept between steps. Instead, we verify the flow handles a
    // nonexistent chat gracefully (similar concurrent-delete scenario).
    //
    // The real CAS=0 path is tested by: upload_file succeeds at step 2 (file
    // upload to provider), but the row was soft-deleted between steps 2 and 4.
    // With SQLite single-writer, true concurrency is hard to simulate.
    //
    // We test the boundary: upload with a provider that works, but the
    // attachment has already been deleted (simulated by inserting a pending
    // row, soft-deleting it, and verifying get_attachment returns NotFound).

    // Insert a pending attachment and immediately soft-delete it
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.status = crate::infra::db::entity::attachment::AttachmentStatus::Pending;
    params.deleted_at = Some(time::OffsetDateTime::now_utc());
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    // Verify that get_attachment returns NotFound for the soft-deleted pending row
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.get_attachment(&ctx, chat_id, att_id).await;
    assert!(result.is_err());
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "soft-deleted pending attachment should return NotFound"
    );
}

// ── P5-F3 (actual): Delete attachment referenced by message → conflict ──

#[tokio::test]
async fn test_delete_attachment_referenced_by_message_conflict() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a ready attachment
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    // Insert parent message row (required by FK), then link attachment to it
    insert_test_message(&db_prov, tenant_id, chat_id, message_id).await;
    crate::domain::service::test_helpers::insert_test_message_attachment(
        &db_prov, tenant_id, chat_id, message_id, att_id,
    )
    .await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.delete_attachment(&ctx, chat_id, att_id).await;
    assert!(
        result.is_err(),
        "delete of referenced attachment should fail"
    );
    let err = result.unwrap_err();
    assert!(
        matches!(err, crate::domain::error::DomainError::Conflict { .. }),
        "expected Conflict (attachment_locked), got: {err:?}"
    );
}

// ── P5-F6: Delete non-existent attachment → 404 (no info leak) ──

#[tokio::test]
async fn test_delete_nonexistent_attachment_returns_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.delete_attachment(&ctx, chat_id, Uuid::new_v4()).await;
    assert!(result.is_err());
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "non-existent attachment should return NotFound, not Forbidden"
    );
}

// ── P5-G1: Get ready attachment ──

#[tokio::test]
async fn test_get_ready_attachment_returns_detail() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.doc_summary = Some("Test summary".to_owned());
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let att = svc.get_attachment(&ctx, chat_id, att_id).await.unwrap();
    assert_eq!(att.id, att_id);
    assert_eq!(
        att.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Ready
    );
    assert_eq!(att.doc_summary.as_deref(), Some("Test summary"));
    assert!(att.deleted_at.is_none());
}

// ── P5-G2: Get pending attachment ──

#[tokio::test]
async fn test_get_pending_attachment_returns_pending() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.status = crate::infra::db::entity::attachment::AttachmentStatus::Pending;
    params.provider_file_id = None;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let att = svc.get_attachment(&ctx, chat_id, att_id).await.unwrap();
    assert_eq!(
        att.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Pending
    );
    assert!(att.doc_summary.is_none());
}

// ── P5-G3: Get non-existent attachment → 404 ──

#[tokio::test]
async fn test_get_nonexistent_attachment_returns_not_found() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = svc.get_attachment(&ctx, chat_id, Uuid::new_v4()).await;
    assert!(result.is_err());
    assert!(
        matches!(
            result.unwrap_err(),
            crate::domain::error::DomainError::NotFound { .. }
        ),
        "random UUID should return NotFound"
    );
}

// ── P5-G4: Get soft-deleted attachment → 404 ──
// (already covered by test_get_attachment_soft_deleted_returns_not_found above)

// ── P5-E1: Vector store winner path (first upload creates VS) ──
// Covered implicitly by test_upload_document_full_lifecycle (P5-B1):
// the first document upload creates a chat_vector_stores row with NULL,
// calls OAGW to create VS, and CAS-sets the vector_store_id.
// We verify explicitly that the VS row exists after a document upload.

#[tokio::test]
async fn test_vector_store_created_on_first_document_upload() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-vs-001")),
        Ok(vector_store_create_response("vs-winner-001")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(
        db.clone(),
        Arc::clone(&oagw) as _,
        outbox,
        RagConfig::default(),
    );

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "doc.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;
    assert!(result.is_ok(), "upload failed: {result:?}");

    // Verify vector store row was created with the OAGW-returned ID
    let vs_repo = OrmVectorStoreRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let vs_row = vs_repo.find_by_chat(&conn, &scope, chat_id).await.unwrap();
    assert!(
        vs_row.is_some(),
        "vector store row should exist after document upload"
    );
    let vs_row = vs_row.unwrap();
    assert_eq!(vs_row.vector_store_id.as_deref(), Some("vs-winner-001"));
}

// ── P5-E5: Pre-existing VS row is reused (no duplicate insert) ──

#[tokio::test]
async fn test_vector_store_preexisting_row_reused() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Pre-insert a vector store row with a populated ID (simulates a previous upload)
    crate::domain::service::test_helpers::insert_test_vector_store(
        &db_prov,
        tenant_id,
        chat_id,
        Some("vs-preexisting".to_owned()),
    )
    .await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Only 2 OAGW calls expected: file upload + add file to VS (no VS create)
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-pre-001")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "doc.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;
    assert!(
        result.is_ok(),
        "upload with preexisting VS failed: {result:?}"
    );

    // Verify only 2 OAGW calls (no vector store creation)
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 2, "should skip VS create when row exists");
    assert!(requests[0].uri.contains("/v1/files"));
    assert!(
        requests[1]
            .uri
            .contains("/v1/vector_stores/vs-preexisting/files"),
        "should use preexisting VS ID, got: {}",
        requests[1].uri
    );
}

// ── P5-E2/E3/E4: Concurrent vector store race conditions ──
// These tests require true concurrency (multiple tasks racing on INSERT).
// With SQLite single-writer in-memory DB, the race window is too narrow to
// reliably trigger. The winner/loser/poll-timeout paths are tested via the
// unit-level logic. E2/E3/E4 are marked as integration-only tests.

// ── P5-M1: Storage within limit after deletions ──

#[tokio::test]
async fn test_storage_within_limit_after_deletions() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let config = RagConfig {
        max_documents_per_chat: 50,
        max_total_upload_mb_per_chat: 1, // 1 MB limit
        ..RagConfig::default()
    };

    // Insert a large attachment that's been soft-deleted
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.size_bytes = 900_000; // 0.86 MB
    params.deleted_at = Some(time::OffsetDateTime::now_utc()); // soft-deleted!
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Upload 0.5 MB — should succeed because deleted attachment doesn't count
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-after-del")),
        Ok(vector_store_create_response("vs-after-del")),
        Ok(vector_store_add_file_response()),
    ]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, config);

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "new.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 500_000]),
    )
    .await;

    assert!(
        result.is_ok(),
        "upload should succeed when deleted rows free space: {result:?}"
    );
}

// ── P5-M2: CAS transition chain pending → uploaded → ready ──

#[tokio::test]
async fn test_cas_transition_chain_full_lifecycle() {
    // This is implicitly tested by test_upload_document_full_lifecycle,
    // which goes pending → uploaded → ready via the upload_file method.
    // Here we verify the final state explicitly shows all transitions completed.
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-cas-chain")),
        Ok(vector_store_create_response("vs-cas-chain")),
        Ok(vector_store_add_file_response()),
    ]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let att = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "chain.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await
    .expect("upload should succeed");

    // Final state is Ready with provider_file_id set (proves pending→uploaded→ready)
    assert_eq!(
        att.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Ready
    );
    assert_eq!(att.provider_file_id.as_deref(), Some("file-cas-chain"));
    assert!(att.error_code.is_none());
}

// ── P5-M3: CAS set_uploaded on ready row → no effect ──
// This is tested indirectly: after upload_file completes, re-uploading the
// same attachment is not possible (each upload creates a new row).
// The CAS WHERE clause (`status = 'pending'`) ensures idempotency.

// ── P5-M4: CAS after soft-delete returns 0 ──
// Tested by P5-D3 (concurrent delete scenario): soft-deleted row causes
// CAS set_uploaded to return 0, which triggers NotFound.

// ── P5-K7: build_provider_file_id_map excludes non-ready ──

#[tokio::test]
async fn test_provider_file_id_map_excludes_non_ready() {
    use crate::domain::repos::AttachmentRepository;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a ready document (should be in map)
    let mut ready_params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    ready_params.uploaded_by_user_id = user_id;
    ready_params.provider_file_id = Some("file-ready".to_owned());
    let ready_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, ready_params).await;

    // Insert an uploaded (not ready) document (should NOT be in map)
    let mut uploaded_params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    uploaded_params.uploaded_by_user_id = user_id;
    uploaded_params.status = crate::infra::db::entity::attachment::AttachmentStatus::Uploaded;
    uploaded_params.provider_file_id = Some("file-uploaded".to_owned());
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, uploaded_params).await;

    // Insert a pending document (should NOT be in map)
    let mut pending_params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    pending_params.uploaded_by_user_id = user_id;
    pending_params.status = crate::infra::db::entity::attachment::AttachmentStatus::Pending;
    pending_params.provider_file_id = None;
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, pending_params).await;

    let repo = crate::infra::db::repo::attachment_repo::AttachmentRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let map = repo
        .build_provider_file_id_map(&conn, &scope, chat_id)
        .await
        .unwrap();

    assert_eq!(map.len(), 1, "only ready attachment should be in map");
    let att = map.get("file-ready").expect("file-ready should be in map");
    assert_eq!(att.id, ready_id);
    assert_eq!(att.filename, "test.pdf");
}

// ── P5-K8: build_provider_file_id_map excludes soft-deleted ──

#[tokio::test]
async fn test_provider_file_id_map_excludes_deleted() {
    use crate::domain::repos::AttachmentRepository;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a ready but soft-deleted document (should NOT be in map)
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.provider_file_id = Some("file-deleted".to_owned());
    params.deleted_at = Some(time::OffsetDateTime::now_utc());
    crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    // Insert a ready, non-deleted document (should be in map)
    let mut alive_params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    alive_params.uploaded_by_user_id = user_id;
    alive_params.provider_file_id = Some("file-alive".to_owned());
    let alive_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, alive_params).await;

    let repo = crate::infra::db::repo::attachment_repo::AttachmentRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let map = repo
        .build_provider_file_id_map(&conn, &scope, chat_id)
        .await
        .unwrap();

    assert_eq!(map.len(), 1, "deleted attachment should not be in map");
    let att = map.get("file-alive").expect("file-alive should be in map");
    assert_eq!(att.id, alive_id);
    assert!(!map.contains_key("file-deleted"));
}

// ── P5-K9: build_provider_file_id_map empty when no ready docs ──

#[tokio::test]
async fn test_provider_file_id_map_empty_no_ready_docs() {
    use crate::domain::repos::AttachmentRepository;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let repo = crate::infra::db::repo::attachment_repo::AttachmentRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let map = repo
        .build_provider_file_id_map(&conn, &scope, chat_id)
        .await
        .unwrap();

    assert!(map.is_empty(), "no ready docs -> empty map");
}

// ── P5-G5: Get attachment from wrong chat ──

#[tokio::test]
async fn test_get_attachment_wrong_chat_returns_not_found() {
    use crate::domain::error::DomainError;
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let other_chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;
    insert_chat_for_user(&db_prov, tenant_id, other_chat_id, user_id).await;

    // Insert attachment in chat_id
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    // Access via wrong chat → not found
    let result = svc.get_attachment(&ctx, other_chat_id, att_id).await;
    assert!(result.is_err(), "wrong chat_id should return error");
    assert!(
        matches!(result.unwrap_err(), DomainError::NotFound { .. }),
        "should be NotFound"
    );
}

// ── P5-G6: Delete attachment from wrong chat ──

#[tokio::test]
async fn test_delete_attachment_wrong_chat_returns_not_found() {
    use crate::domain::error::DomainError;
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let other_chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;
    insert_chat_for_user(&db_prov, tenant_id, other_chat_id, user_id).await;

    // Insert attachment in chat_id
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    // Delete via wrong chat → not found
    let result = svc.delete_attachment(&ctx, other_chat_id, att_id).await;
    assert!(result.is_err(), "wrong chat_id should return error");
    assert!(
        matches!(result.unwrap_err(), DomainError::NotFound { .. }),
        "should be NotFound"
    );
}

// ── REAL-5: Enqueue failure rolls back soft-delete ──

#[tokio::test]
async fn test_enqueue_failure_rolls_back_soft_delete() {
    use crate::domain::repos::AttachmentRepository;
    use crate::domain::service::test_helpers::FailingOutboxEnqueuer;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Insert a ready attachment (not referenced by messages)
    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);
    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox: Arc<dyn crate::domain::repos::OutboxEnqueuer> = Arc::new(FailingOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    // Try to delete — outbox enqueue will fail, should roll back soft-delete
    let result = svc.delete_attachment(&ctx, chat_id, att_id).await;
    assert!(
        result.is_err(),
        "delete should fail when outbox enqueue fails"
    );

    // Verify: attachment is still NOT soft-deleted (rollback)
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let repo = OrmAttachmentRepository;
    let row = repo.get(&conn, &scope, att_id).await.unwrap();
    assert!(row.is_some(), "attachment should still exist");
    let row = row.unwrap();
    assert!(
        row.deleted_at.is_none(),
        "soft-delete should have been rolled back"
    );
}

// ── P5-M5: CAS set_failed from pending ──

#[tokio::test]
async fn test_cas_set_failed_from_pending() {
    use crate::domain::repos::AttachmentRepository;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.status = crate::infra::db::entity::attachment::AttachmentStatus::Pending;
    params.provider_file_id = None;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let repo = crate::infra::db::repo::attachment_repo::AttachmentRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();

    let affected = repo
        .cas_set_failed(
            &conn,
            &scope,
            crate::domain::repos::SetFailedParams {
                id: att_id,
                error_code: "upload_failed".to_owned(),
                from_status: "pending".to_owned(),
            },
        )
        .await
        .unwrap();
    assert_eq!(affected, 1, "CAS pending->failed should affect 1 row");

    // Verify final state
    let row = repo.get(&conn, &scope, att_id).await.unwrap().unwrap();
    assert_eq!(
        row.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Failed
    );
    assert_eq!(row.error_code.as_deref(), Some("upload_failed"));
}

// ── P5-M6: CAS set_failed from uploaded ──

#[tokio::test]
async fn test_cas_set_failed_from_uploaded() {
    use crate::domain::repos::AttachmentRepository;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let mut params =
        crate::domain::service::test_helpers::InsertTestAttachmentParams::ready_document(
            tenant_id, chat_id,
        );
    params.uploaded_by_user_id = user_id;
    params.status = crate::infra::db::entity::attachment::AttachmentStatus::Uploaded;
    let att_id =
        crate::domain::service::test_helpers::insert_test_attachment(&db_prov, params).await;

    let repo = crate::infra::db::repo::attachment_repo::AttachmentRepository;
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();

    let affected = repo
        .cas_set_failed(
            &conn,
            &scope,
            crate::domain::repos::SetFailedParams {
                id: att_id,
                error_code: "indexing_failed".to_owned(),
                from_status: "uploaded".to_owned(),
            },
        )
        .await
        .unwrap();
    assert_eq!(affected, 1, "CAS uploaded->failed should affect 1 row");

    let row = repo.get(&conn, &scope, att_id).await.unwrap().unwrap();
    assert_eq!(
        row.status,
        crate::infra::db::entity::attachment::AttachmentStatus::Failed
    );
    assert_eq!(row.error_code.as_deref(), Some("indexing_failed"));
}

// ── P5-M8: FileSearchFilter::attachment_in panics on empty ──

#[test]
#[should_panic(expected = "attachment_in called with empty ids")]
fn test_attachment_in_panics_on_empty() {
    use crate::domain::llm::FileSearchFilter;
    drop(FileSearchFilter::attachment_in(&[]));
}

// ── Azure provider helpers ──

/// Build a `MockModelResolver` with an `azure_openai` model entry.
fn azure_model_resolver() -> Arc<dyn crate::domain::repos::ModelResolver> {
    Arc::new(MockModelResolver::new(vec![test_catalog_entry(
        TestCatalogEntryParams {
            model_id: "gpt-5.2-azure".to_owned(),
            provider_model_id: "gpt-5.2-2025-03-26".to_owned(),
            display_name: "GPT-5.2 (Azure)".to_owned(),
            tier: mini_chat_sdk::ModelTier::Premium,
            enabled: true,
            is_default: true,
            input_tokens_credit_multiplier_micro: 2_000_000,
            output_tokens_credit_multiplier_micro: 6_000_000,
            multimodal_capabilities: vec![],
            context_window: 128_000,
            max_output_tokens: 16_384,
            description: String::new(),
            provider_display_name: "Azure OpenAI".to_owned(),
            multiplier_display: "2x".to_owned(),
            provider_id: "azure_openai".to_owned(),
        },
    )]))
}

/// Build a `ProviderResolver` with both `"openai"` and `"azure_openai"` entries.
fn dual_provider_resolver(
    oagw: &Arc<dyn oagw_sdk::ServiceGatewayClientV1>,
) -> Arc<ProviderResolver> {
    let mut providers = HashMap::new();
    providers.insert(
        "openai".to_owned(),
        ProviderEntry {
            kind: ProviderKind::OpenAiResponses,
            upstream_alias: Some("test-host".to_owned()),
            host: "test-host".to_owned(),
            port: None,
            use_http: false,
            api_path: "/v1/responses".to_owned(),
            auth_plugin_type: None,
            auth_config: None,
            storage_backend: None,
            supports_file_search_filters: true,
            storage_kind: StorageKind::OpenAi,
            api_version: None,
            tenant_overrides: HashMap::new(),
        },
    );
    providers.insert(
        "azure_openai".to_owned(),
        ProviderEntry {
            kind: ProviderKind::OpenAiResponses,
            upstream_alias: Some("azure-host".to_owned()),
            host: "azure-host".to_owned(),
            port: None,
            use_http: false,
            api_path: "/v1/responses".to_owned(),
            auth_plugin_type: None,
            auth_config: None,
            storage_backend: Some("azure".to_owned()),
            supports_file_search_filters: false,
            storage_kind: StorageKind::Azure,
            api_version: Some("2024-10-21".to_owned()),
            tenant_overrides: HashMap::new(),
        },
    );
    Arc::new(ProviderResolver::new(oagw, providers))
}

/// Build an `AttachmentService` wired for `azure_openai` provider tests.
fn build_service_azure(
    db: modkit_db::Db,
    oagw: Arc<dyn oagw_sdk::ServiceGatewayClientV1>,
    outbox: Arc<dyn crate::domain::repos::OutboxEnqueuer>,
    rag_config: RagConfig,
) -> TestAttachmentService {
    let db = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(modkit_db::odata::LimitCfg {
        default: 20,
        max: 100,
    }));
    let attachment_repo = Arc::new(OrmAttachmentRepository);
    let vector_store_repo = Arc::new(OrmVectorStoreRepository);
    let provider_resolver = dual_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client =
        Arc::new(crate::infra::llm::providers::rag_http_client::RagHttpClient::new(oagw));
    // Build dispatching wrappers with both OpenAI and Azure impls
    let mut file_impls: HashMap<String, Arc<dyn crate::domain::ports::FileStorageProvider>> =
        HashMap::new();
    let mut vs_impls: HashMap<String, Arc<dyn crate::domain::ports::VectorStoreProvider>> =
        HashMap::new();
    for (provider_id, entry) in provider_resolver.entries() {
        let (file, vs): (
            Arc<dyn crate::domain::ports::FileStorageProvider>,
            Arc<dyn crate::domain::ports::VectorStoreProvider>,
        ) = match entry.storage_kind {
            crate::config::StorageKind::Azure => {
                let ver = entry
                    .api_version
                    .clone()
                    .expect("Azure requires api_version");
                (
                    Arc::new(
                        crate::infra::llm::providers::azure_file_storage::AzureFileStorage::new(
                            Arc::clone(&rag_client),
                            Arc::clone(&provider_resolver),
                            ver.clone(),
                        ),
                    ),
                    Arc::new(
                        crate::infra::llm::providers::azure_vector_store::AzureVectorStore::new(
                            Arc::clone(&rag_client),
                            Arc::clone(&provider_resolver),
                            ver,
                        ),
                    ),
                )
            }
            crate::config::StorageKind::OpenAi => (
                Arc::new(
                    crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
                        Arc::clone(&rag_client),
                        Arc::clone(&provider_resolver),
                    ),
                ),
                Arc::new(
                    crate::infra::llm::providers::openai_vector_store::OpenAiVectorStore::new(
                        Arc::clone(&rag_client),
                        Arc::clone(&provider_resolver),
                    ),
                ),
            ),
        };
        file_impls.insert(provider_id.clone(), file);
        vs_impls.insert(provider_id.clone(), vs);
    }
    let file_storage: Arc<dyn crate::domain::ports::FileStorageProvider> = Arc::new(
        crate::infra::llm::providers::dispatching_storage::DispatchingFileStorage::new(file_impls),
    );
    let vector_store_prov: Arc<dyn crate::domain::ports::VectorStoreProvider> = Arc::new(
        crate::infra::llm::providers::dispatching_storage::DispatchingVectorStore::new(vs_impls),
    );

    AttachmentService::new(
        db,
        attachment_repo,
        chat_repo,
        vector_store_repo,
        outbox,
        mock_tenant_only_enforcer(),
        file_storage,
        vector_store_prov,
        provider_resolver,
        azure_model_resolver(),
        rag_config,
        crate::config::ThumbnailConfig::default(),
        Arc::new(crate::domain::ports::metrics::NoopMetrics),
    )
}

// ── 1.10: Azure provider — all 4 HTTP calls use same upstream_alias ──

#[tokio::test]
async fn test_upload_document_azure_provider_all_calls_same_alias() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_with_model(&db_prov, tenant_id, chat_id, user_id, "gpt-5.2-azure").await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // 3 OAGW responses: file upload → VS create → add file to VS
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-azure-001")),
        Ok(vector_store_create_response("vs-azure-001")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service_azure(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "report.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 1024]),
    )
    .await;

    assert!(result.is_ok(), "azure upload_file failed: {result:?}");

    // Verify ALL 3 OAGW calls use the azure upstream_alias ("azure-host")
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 3, "expected 3 OAGW calls for azure upload");

    for (i, req) in requests.iter().enumerate() {
        assert!(
            req.uri.starts_with("/azure-host/"),
            "call {i} should use azure-host alias, got URI: {}",
            req.uri
        );
    }

    // Verify call types — Azure uses /openai prefix with api-version query param
    assert!(
        requests[0].uri.contains("/openai/files"),
        "1st: file upload"
    );
    assert!(
        requests[1].uri.contains("/openai/vector_stores") && !requests[1].uri.contains("/files"),
        "2nd: VS create"
    );
    assert!(
        requests[2]
            .uri
            .contains("/openai/vector_stores/vs-azure-001/files"),
        "3rd: add file to VS"
    );
}

// ── 1.11: Azure full lifecycle — storage_backend and VS provider persisted ──

#[tokio::test]
async fn test_upload_document_azure_storage_backend_and_vs_provider_persisted() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_with_model(&db_prov, tenant_id, chat_id, user_id, "gpt-5.2-azure").await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-azure-002")),
        Ok(vector_store_create_response("vs-azure-002")),
        Ok(vector_store_add_file_response()),
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service_azure(
        db.clone(),
        Arc::clone(&oagw) as _,
        outbox,
        RagConfig::default(),
    );

    let attachment = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "doc.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 512]),
    )
    .await
    .expect("azure upload should succeed");

    // Verify attachment storage_backend = "azure" (from config field, not "azure_openai")
    assert_eq!(
        attachment.storage_backend, "azure",
        "storage_backend should be 'azure' (resolved from config), not 'azure_openai'"
    );

    // Verify vector store row has provider = "azure"
    let conn = db_prov.conn().unwrap();
    let scope = modkit_security::AccessScope::allow_all();
    let vs_row = OrmVectorStoreRepository
        .find_by_chat(&conn, &scope, chat_id)
        .await
        .expect("VS query should succeed")
        .expect("VS row should exist after upload");
    assert_eq!(
        vs_row.provider, "azure",
        "VS provider should be 'azure' matching storage_backend"
    );
}

// ── 1.12: Second upload to chat with existing VS — provider mismatch rejected ──

#[tokio::test]
async fn test_second_upload_provider_mismatch_rejected() {
    use crate::domain::service::test_helpers::insert_test_vector_store_with_provider;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    // Chat uses the default openai model (gpt-5.2)
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    // Pre-insert a vector store with provider="azure" (simulating a previous azure upload)
    insert_test_vector_store_with_provider(
        &db_prov,
        tenant_id,
        chat_id,
        Some("vs-pre-existing".to_owned()),
        "azure",
    )
    .await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Upload resolves to openai (storage_backend="openai") but VS has provider="azure" → mismatch
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-oa-mismatch")),
        // No VS create/add responses — should fail at provider consistency check
    ]);

    let outbox = Arc::new(NoopOutboxEnqueuer);
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, RagConfig::default());

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "b.pdf",
        "application/pdf",
        Bytes::from(vec![0u8; 100]),
    )
    .await;

    assert!(result.is_err(), "provider mismatch should be rejected");
    let err = result.unwrap_err();
    let err_str = format!("{err:?}");
    assert!(
        err_str.contains("provider_mismatch") || err_str.contains("mismatch"),
        "error should mention provider mismatch, got: {err_str}"
    );
}

// ── P5-I through P5-L, P5-N: SendMessage integration and E2E tests ──
// These require the full stream service with TurnOrchestrator, quota, SSE
// streaming, and citation mapping pipeline. Deferred to stream_service_test.rs
// and pytest E2E respectively.

// ══════════════════════════════════════════════════════════════════════════════
// WS3 Phase 2: Provider-specific impl and dispatching tests
// ══════════════════════════════════════════════════════════════════════════════

use crate::domain::ports::FileStorageProvider;

// ── 3b.14: RagHttpClient multipart body uses params.purpose ──

#[tokio::test]
async fn test_rag_http_client_multipart_uses_params_purpose() {
    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-001"))]);
    let client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );
    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);

    let params = crate::domain::ports::UploadFileParams {
        filename: "test.txt".to_owned(),
        content_type: "text/plain".to_owned(),
        file_stream: bytes_to_stream(Bytes::from("hello")),
        purpose: "user_data".to_owned(),
    };

    let result = client
        .multipart_upload(ctx, "/test-host/v1/files", params)
        .await;
    assert!(result.is_ok(), "upload failed: {result:?}");
    assert_eq!(result.unwrap().0, "file-001");

    // Verify the multipart body contains the custom purpose, not hardcoded "assistants"
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 1);
    let body = &requests[0].body;
    let body_str = String::from_utf8_lossy(body.as_bytes());
    assert!(
        body_str.contains("user_data"),
        "multipart body should contain custom purpose 'user_data', got: {body_str}"
    );
    assert!(
        !body_str.contains("assistants"),
        "multipart body should NOT contain hardcoded 'assistants'"
    );
}

#[tokio::test]
async fn test_rag_http_client_json_post_parses_response() {
    #[derive(serde::Deserialize)]
    struct Resp {
        id: String,
    }
    let response_json = serde_json::json!({ "id": "vs-001" });
    let oagw = MockOagwGateway::with_responses(vec![Ok(response_json)]);
    let client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );
    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);

    let result: Result<Resp, _> = client
        .json_post(ctx, "/test-host/v1/vector_stores", &serde_json::json!({}))
        .await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().id, "vs-001");
}

// ── 3b.15: OpenAiFileStorage URI pattern ──

#[tokio::test]
async fn test_openai_file_storage_uri_pattern() {
    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-001"))]);
    let resolver = test_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );
    let storage = crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
        rag_client, resolver,
    );
    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);

    let params = crate::domain::ports::UploadFileParams {
        filename: "test.txt".to_owned(),
        content_type: "text/plain".to_owned(),
        file_stream: bytes_to_stream(Bytes::from("hello")),
        purpose: "assistants".to_owned(),
    };

    let result = storage.upload_file(ctx, "openai", params).await;
    assert!(result.is_ok(), "upload failed: {result:?}");

    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 1);
    // OpenAI pattern: /{alias}/v1/files, no query params
    assert!(
        requests[0].uri.starts_with("/test-host/v1/files"),
        "OpenAI URI should be /{{alias}}/v1/files, got: {}",
        requests[0].uri
    );
    assert!(
        !requests[0].uri.contains("api-version"),
        "OpenAI URI should NOT have api-version query param"
    );
}

// ── 3b.16: AzureFileStorage URI pattern ──

#[tokio::test]
async fn test_azure_file_storage_uri_pattern() {
    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-az-001"))]);
    let resolver = dual_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );
    let storage = crate::infra::llm::providers::azure_file_storage::AzureFileStorage::new(
        rag_client,
        resolver,
        "2025-03-01-preview".to_owned(),
    );
    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);

    let params = crate::domain::ports::UploadFileParams {
        filename: "test.txt".to_owned(),
        content_type: "text/plain".to_owned(),
        file_stream: bytes_to_stream(Bytes::from("hello")),
        purpose: "assistants".to_owned(),
    };

    let result = storage.upload_file(ctx, "azure_openai", params).await;
    assert!(result.is_ok(), "upload failed: {result:?}");

    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 1);
    // Azure pattern: /{alias}/openai/files?api-version=…
    assert!(
        requests[0].uri.starts_with("/azure-host/openai/files"),
        "Azure URI should be /{{alias}}/openai/files, got: {}",
        requests[0].uri
    );
    assert!(
        requests[0].uri.contains("api-version=2025-03-01-preview"),
        "Azure URI should have api-version query param, got: {}",
        requests[0].uri
    );
}

// ── 3b.17: DispatchingFileStorage routes by provider_id ──

#[tokio::test]
async fn test_dispatching_file_storage_routes_correctly() {
    // Queue 2 responses: one for OpenAI, one for Azure
    let oagw = MockOagwGateway::with_responses(vec![
        Ok(file_upload_response("file-oai-001")),
        Ok(file_upload_response("file-az-001")),
    ]);
    let resolver = dual_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );

    let mut impls: HashMap<String, Arc<dyn crate::domain::ports::FileStorageProvider>> =
        HashMap::new();
    impls.insert(
        "openai".to_owned(),
        Arc::new(
            crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
                Arc::clone(&rag_client),
                Arc::clone(&resolver),
            ),
        ),
    );
    impls.insert(
        "azure_openai".to_owned(),
        Arc::new(
            crate::infra::llm::providers::azure_file_storage::AzureFileStorage::new(
                rag_client,
                resolver,
                "2024-10-21".to_owned(),
            ),
        ),
    );
    let dispatch =
        crate::infra::llm::providers::dispatching_storage::DispatchingFileStorage::new(impls);

    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);

    // Upload via OpenAI
    let r1: Result<(String, u64), _> = dispatch
        .upload_file(
            ctx.clone(),
            "openai",
            crate::domain::ports::UploadFileParams {
                filename: "test.txt".to_owned(),
                content_type: "text/plain".to_owned(),
                file_stream: bytes_to_stream(Bytes::from("hello")),
                purpose: "assistants".to_owned(),
            },
        )
        .await;
    assert!(r1.is_ok());
    assert_eq!(r1.unwrap().0, "file-oai-001");

    // Upload via Azure
    let r2: Result<(String, u64), _> = dispatch
        .upload_file(
            ctx.clone(),
            "azure_openai",
            crate::domain::ports::UploadFileParams {
                filename: "test.txt".to_owned(),
                content_type: "text/plain".to_owned(),
                file_stream: bytes_to_stream(Bytes::from("hello")),
                purpose: "assistants".to_owned(),
            },
        )
        .await;
    assert!(r2.is_ok());
    assert_eq!(r2.unwrap().0, "file-az-001");

    // Verify routing: first request → /v1/, second → /openai/
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 2);
    assert!(
        requests[0].uri.contains("/v1/files"),
        "first request should use /v1/ pattern, got: {}",
        requests[0].uri
    );
    assert!(
        requests[1].uri.contains("/openai/files"),
        "second request should use /openai/ pattern, got: {}",
        requests[1].uri
    );
}

#[tokio::test]
async fn test_dispatching_file_storage_unknown_provider_returns_error() {
    let dispatch = crate::infra::llm::providers::dispatching_storage::DispatchingFileStorage::new(
        HashMap::new(),
    );
    let tenant_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx(tenant_id);
    let params = crate::domain::ports::UploadFileParams {
        filename: "test.txt".to_owned(),
        content_type: "text/plain".to_owned(),
        file_stream: bytes_to_stream(Bytes::from("hello")),
        purpose: "assistants".to_owned(),
    };

    let result: Result<(String, u64), _> = dispatch.upload_file(ctx, "nonexistent", params).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(
            err,
            crate::domain::ports::FileStorageError::Configuration { .. }
        ),
        "expected Configuration error for unknown provider, got: {err:?}"
    );
}

// ── 3b.18: Tenant-aware alias resolution ──

#[tokio::test]
async fn test_openai_file_storage_uses_tenant_specific_alias() {
    use crate::config::ProviderTenantOverride;
    use crate::infra::llm::providers::ProviderKind;

    // Create provider with tenant override that has a different upstream alias
    let mut providers = HashMap::new();
    let mut tenant_overrides = HashMap::new();
    let tenant_id = Uuid::new_v4();
    tenant_overrides.insert(
        tenant_id.to_string(),
        ProviderTenantOverride {
            host: Some("tenant-specific.openai.com".to_owned()),
            upstream_alias: Some("tenant-alias".to_owned()),
            auth_plugin_type: None,
            auth_config: None,
        },
    );
    providers.insert(
        "openai".to_owned(),
        ProviderEntry {
            kind: ProviderKind::OpenAiResponses,
            upstream_alias: Some("default-alias".to_owned()),
            host: "api.openai.com".to_owned(),
            port: None,
            use_http: false,
            api_path: "/v1/responses".to_owned(),
            auth_plugin_type: None,
            auth_config: None,
            storage_backend: None,
            supports_file_search_filters: true,
            storage_kind: StorageKind::OpenAi,
            api_version: None,
            tenant_overrides,
        },
    );

    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-001"))]);
    let resolver = Arc::new(ProviderResolver::new(&(Arc::clone(&oagw) as _), providers));
    let rag_client = Arc::new(
        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(Arc::clone(&oagw) as _),
    );
    let storage = crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
        rag_client, resolver,
    );

    // Create ctx with the tenant that has an override
    let user_id = Uuid::new_v4();
    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    let params = crate::domain::ports::UploadFileParams {
        filename: "test.txt".to_owned(),
        content_type: "text/plain".to_owned(),
        file_stream: bytes_to_stream(Bytes::from("hello")),
        purpose: "assistants".to_owned(),
    };

    let result = storage.upload_file(ctx, "openai", params).await;
    assert!(result.is_ok(), "upload failed: {result:?}");

    // Verify the request used the TENANT-SPECIFIC alias, not the default
    let requests = oagw.captured_requests.lock().unwrap();
    assert_eq!(requests.len(), 1);
    assert!(
        requests[0].uri.starts_with("/tenant-alias/v1/files"),
        "should use tenant-specific alias 'tenant-alias', got: {}",
        requests[0].uri
    );
}

// ════════════════════════════════════════════════════════════════════════════
// Upload limits resolution (get_upload_context)
// ════════════════════════════════════════════════════════════════════════════

/// CCM per-model limit is tighter than `ConfigMap` → effective = CCM.
#[tokio::test]
async fn test_upload_limits_ccm_tighter_than_configmap() {
    use mini_chat_sdk::ModelTier;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    // Model with max_file_size_mb = 10 (tighter than ConfigMap's 25 MB default)
    let mut entry = test_catalog_entry(TestCatalogEntryParams {
        model_id: "gpt-5.2".to_owned(),
        provider_model_id: "gpt-5.2-2025-03-26".to_owned(),
        display_name: "GPT 5.2".to_owned(),
        tier: ModelTier::Standard,
        enabled: true,
        is_default: true,
        input_tokens_credit_multiplier_micro: 1_000_000,
        output_tokens_credit_multiplier_micro: 3_000_000,
        multimodal_capabilities: vec![],
        context_window: 128_000,
        max_output_tokens: 16_384,
        description: String::new(),
        provider_display_name: "OpenAI".to_owned(),
        multiplier_display: "1x".to_owned(),
        provider_id: "openai".to_owned(),
    });
    entry.general_config.max_file_size_mb = 10; // 10 MB — tighter than 25 MB default

    let model_resolver: Arc<dyn crate::domain::repos::ModelResolver> =
        Arc::new(MockModelResolver::new(vec![entry]));

    let oagw = MockOagwGateway::with_responses(vec![]);
    let db_prov_arc = mock_db_provider(db.clone());
    let provider_resolver = test_provider_resolver(&(Arc::clone(&oagw) as _));
    let rag_config = RagConfig::default();

    let svc =
        AttachmentService::new(
            db_prov_arc,
            Arc::new(OrmAttachmentRepository),
            Arc::new(OrmChatRepository::new(modkit_db::odata::LimitCfg {
                default: 20,
                max: 100,
            })),
            Arc::new(OrmVectorStoreRepository),
            Arc::new(NoopOutboxEnqueuer),
            mock_tenant_only_enforcer(),
            Arc::new(
                crate::infra::llm::providers::openai_file_storage::OpenAiFileStorage::new(
                    Arc::new(
                        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(
                            Arc::clone(&oagw) as _,
                        ),
                    ),
                    Arc::clone(&provider_resolver),
                ),
            ),
            Arc::new(
                crate::infra::llm::providers::openai_vector_store::OpenAiVectorStore::new(
                    Arc::new(
                        crate::infra::llm::providers::rag_http_client::RagHttpClient::new(
                            Arc::clone(&oagw) as _,
                        ),
                    ),
                    Arc::clone(&provider_resolver),
                ),
            ),
            provider_resolver,
            model_resolver,
            rag_config,
            crate::config::ThumbnailConfig::default(),
            Arc::new(crate::domain::ports::metrics::NoopMetrics),
        );

    let upload_ctx = svc.get_upload_context(&ctx, chat_id).await.unwrap();

    // CCM = 10 MB = 10_485_760 bytes; ConfigMap = 25 MB = 25_600 KB * 1024 = 26_214_400
    // Effective = min(26_214_400, 10_485_760) = 10_485_760
    assert_eq!(upload_ctx.limits.max_file_bytes, 10_485_760);
    // Image: ConfigMap = 5 MB = 5_242_880; CCM = 10_485_760; effective = 5_242_880
    assert_eq!(upload_ctx.limits.max_image_bytes, 5_242_880);
}

/// `ConfigMap` limit is tighter than CCM → effective = `ConfigMap`.
#[tokio::test]
async fn test_upload_limits_configmap_tighter_than_ccm() {
    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    let oagw = MockOagwGateway::with_responses(vec![]);
    let outbox = Arc::new(NoopOutboxEnqueuer);

    // ConfigMap with very small file limit (1 KB)
    let rag_config = RagConfig {
        uploaded_file_max_size_kb: 1,
        ..RagConfig::default()
    };
    let svc = build_service(db, Arc::clone(&oagw) as _, outbox, rag_config);

    let upload_ctx = svc.get_upload_context(&ctx, chat_id).await.unwrap();

    // ConfigMap = 1 KB = 1024 bytes; CCM default = 25 MB; effective = 1024
    assert_eq!(upload_ctx.limits.max_file_bytes, 1024);
}

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

/// Successful image upload emits upload counter, bytes histogram, and
/// the pending gauge returns to zero (`PendingGuard` balanced).
#[tokio::test]
async fn upload_image_emits_metrics_and_gauge_balanced() {
    use crate::domain::service::test_helpers::TestMetrics;
    use std::sync::atomic::Ordering;

    let db = inmem_db().await;
    let tenant_id = Uuid::new_v4();
    let chat_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();
    let db_prov = mock_db_provider(db.clone());
    insert_chat_for_user(&db_prov, tenant_id, chat_id, user_id).await;

    let ctx = crate::domain::service::test_helpers::test_security_ctx_with_id(tenant_id, user_id);

    let oagw = MockOagwGateway::with_responses(vec![Ok(file_upload_response("file-img-m1"))]);
    let outbox = Arc::new(NoopOutboxEnqueuer);
    let metrics = Arc::new(TestMetrics::new());
    let svc = build_service_with_metrics(
        db,
        Arc::clone(&oagw) as _,
        outbox,
        RagConfig::default(),
        Arc::clone(&metrics) as _,
    );

    let result = test_upload_file(
        &svc,
        &ctx,
        chat_id,
        "photo.png",
        "image/png",
        Bytes::from(vec![0u8; 2048]),
    )
    .await;
    assert!(result.is_ok(), "upload should succeed: {result:?}");

    assert_eq!(
        metrics.attachment_upload.load(Ordering::Relaxed),
        1,
        "should record attachment_upload counter"
    );
    assert_eq!(
        metrics.attachment_upload_bytes.load(Ordering::Relaxed),
        1,
        "should record attachment_upload_bytes histogram"
    );
    assert_eq!(
        metrics.attachments_pending.load(Ordering::Relaxed),
        0,
        "pending gauge should be back to zero (guard balanced)"
    );
}