whatsapp-rust 0.7.0

Rust client for WhatsApp Web
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
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
//! Client integration and unit tests.

use super::*;
use crate::lid_pn_cache::LearningSource;
use crate::test_utils::MockHttpClient;
use futures::channel::oneshot;
use wacore_binary::SERVER_JID;

#[tokio::test]
async fn test_ack_behavior_for_incoming_stanzas() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // --- Assertions ---

    // Verify that we still ack other critical stanzas (regression check).
    use wacore_binary::{Attrs, Node, NodeContent};

    let mut receipt_attrs = Attrs::new();
    receipt_attrs.insert("from".to_string(), "@s.whatsapp.net".to_string());
    receipt_attrs.insert("id".to_string(), "RCPT-1".to_string());
    let receipt_node = Node::new(
        "receipt",
        receipt_attrs,
        Some(NodeContent::String("test".into())),
    );

    let mut notification_attrs = Attrs::new();
    notification_attrs.insert("from".to_string(), "@s.whatsapp.net".to_string());
    notification_attrs.insert("id".to_string(), "NOTIF-1".to_string());
    let notification_node = Node::new(
        "notification",
        notification_attrs,
        Some(NodeContent::String("test".into())),
    );

    assert!(
        client.should_ack(&receipt_node.as_node_ref()),
        "should_ack must still return TRUE for <receipt> stanzas."
    );
    assert!(
        client.should_ack(&notification_node.as_node_ref()),
        "should_ack must still return TRUE for <notification> stanzas."
    );

    // Regular <message> stanzas (DM / group) are acked via the delivery
    // <receipt>, not a bare <ack class="message">. WA Web only emits
    // <ack class="message"> for newsletter deliveries.
    let mut dm_attrs = Attrs::new();
    dm_attrs.insert(
        "from".to_string(),
        "5511999999999@s.whatsapp.net".to_string(),
    );
    dm_attrs.insert("id".to_string(), "MSG-DM-1".to_string());
    let dm_message = Node::new("message", dm_attrs, None);
    assert!(
        !client.should_ack(&dm_message.as_node_ref()),
        "should_ack must return FALSE for regular DM <message> (delivery receipt covers it)."
    );

    let mut group_attrs = Attrs::new();
    group_attrs.insert("from".to_string(), "120363098765432100@g.us".to_string());
    group_attrs.insert("id".to_string(), "MSG-GROUP-1".to_string());
    let group_message = Node::new("message", group_attrs, None);
    assert!(
        !client.should_ack(&group_message.as_node_ref()),
        "should_ack must return FALSE for group <message>."
    );

    let mut newsletter_attrs = Attrs::new();
    newsletter_attrs.insert(
        "from".to_string(),
        "120363298765432100@newsletter".to_string(),
    );
    newsletter_attrs.insert("id".to_string(), "MSG-NL-1".to_string());
    let newsletter_message = Node::new("message", newsletter_attrs, None);
    assert!(
        client.should_ack(&newsletter_message.as_node_ref()),
        "should_ack must return TRUE for newsletter <message>."
    );

    // status@broadcast gets the transport <ack> as a fallback so that
    // drop paths in process_group_enc_batch (expired status, missing
    // sender key, decrypt error) don't leave the server retransmitting.
    // The success path also emits <receipt context="status">; the
    // duplicate is tolerated.
    let mut status_attrs = Attrs::new();
    status_attrs.insert("from".to_string(), "status@broadcast".to_string());
    status_attrs.insert("id".to_string(), "MSG-STATUS-1".to_string());
    let status_message = Node::new("message", status_attrs, None);
    assert!(
        client.should_ack(&status_message.as_node_ref()),
        "should_ack must return TRUE for status@broadcast <message> (fallback for drop paths)."
    );

    // A status update delivered as a top-level <status> stanza is owed the same
    // transport ack; the server recycles the stream until it arrives.
    let mut status_stanza_attrs = Attrs::new();
    status_stanza_attrs.insert("from".to_string(), "status@broadcast".to_string());
    status_stanza_attrs.insert("id".to_string(), "STATUS-STANZA-1".to_string());
    status_stanza_attrs.insert("participant".to_string(), "200725430796339@lid".to_string());
    status_stanza_attrs.insert("type".to_string(), "media".to_string());
    let status_stanza = Node::new("status", status_stanza_attrs, None);
    assert!(
        client.should_ack(&status_stanza.as_node_ref()),
        "should_ack must return TRUE for a top-level <status> stanza."
    );

    info!(
        "✅ test_ack_behavior_for_incoming_stanzas passed: Client correctly differentiates which stanzas to acknowledge."
    );
}

#[tokio::test]
async fn test_ack_waiter_resolves() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // 1. Insert a waiter for a specific ID
    let test_id = "ack-test-123".to_string();
    let (tx, rx) = oneshot::channel();
    client
        .response_waiters_guard()
        .insert(test_id.clone(), ResponseWaiter::Iq(tx));
    assert!(
        client.response_waiters_guard().contains_key(&test_id),
        "Waiter should be inserted before handling ack"
    );

    // 2. Create a mock <ack/> node with the test ID
    let ack_node = NodeBuilder::new("ack")
        .attr("id", test_id.clone())
        .attr("from", SERVER_JID)
        .build();

    // 3. Handle the ack
    let handled = client.handle_ack_response_arc(&Arc::new(to_owned_node(&ack_node)));
    assert!(
        handled,
        "handle_ack_response should return true when waiter exists"
    );

    // 4. Await the receiver with a timeout
    match tokio::time::timeout(Duration::from_secs(1), rx).await {
        Ok(Ok(response_node)) => {
            assert!(
                response_node
                    .get()
                    .get_attr("id")
                    .is_some_and(|v| v.as_str() == test_id.as_str()),
                "Response node should have correct ID"
            );
        }
        Ok(Err(_)) => panic!("Receiver was dropped without being sent a value"),
        Err(_) => panic!("Test timed out waiting for ack response"),
    }

    // 5. Verify the waiter was removed
    assert!(
        !client.response_waiters_guard().contains_key(&test_id),
        "Waiter should be removed after handling"
    );

    info!("✅ test_ack_waiter_resolves passed: ACK response correctly resolves pending waiters");
}

#[tokio::test]
async fn test_ack_without_matching_waiter() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Create an ack without any matching waiter
    let ack_node = NodeBuilder::new("ack")
        .attr("id", "non-existent-id")
        .attr("from", SERVER_JID)
        .build();

    // Should return false since there's no waiter
    let handled = client.handle_ack_response_arc(&Arc::new(to_owned_node(&ack_node)));
    assert!(
        !handled,
        "handle_ack_response should return false when no waiter exists"
    );

    info!(
        "✅ test_ack_without_matching_waiter passed: ACK without matching waiter handled gracefully"
    );
}

/// Round-trip a built `Node` into the raw-bytes shape `unpack()` produces
/// from the network (marshal_ref prepends a 0x00 format byte that
/// `OwnedNodeRef::new` does not expect).
fn to_owned_node(node: &Node) -> wacore_binary::OwnedNodeRef {
    wacore_binary::marshal::marshal_ref(&node.as_node_ref())
        .and_then(|buf| wacore_binary::OwnedNodeRef::new(bytes::Bytes::from(buf).slice(1..)))
        .expect("valid node")
}

fn owned_ack_node(id: &str) -> wacore_binary::OwnedNodeRef {
    to_owned_node(
        &NodeBuilder::new("ack")
            .attr("id", id)
            .attr("from", SERVER_JID)
            .build(),
    )
}

/// The Arc entry point must hand the waiter the SAME allocation it was given
/// (no re-encode + re-parse round trip).
#[tokio::test]
async fn ack_arc_delivery_shares_allocation() {
    let client = crate::test_utils::create_test_client().await;

    let test_id = "ack-arc-456";
    let (tx, rx) = oneshot::channel();
    client
        .response_waiters_guard()
        .insert(test_id.to_string(), ResponseWaiter::Iq(tx));

    let node = Arc::new(owned_ack_node(test_id));
    assert!(client.handle_ack_response_arc(&node));

    let received = tokio::time::timeout(Duration::from_secs(1), rx)
        .await
        .expect("waiter should resolve")
        .expect("sender must not drop");
    assert!(
        Arc::ptr_eq(&received, &node),
        "waiter must receive the original allocation, not a re-encoded copy"
    );

    // No waiter: must report unhandled without consuming anything.
    assert!(!client.handle_ack_response_arc(&Arc::new(owned_ack_node("ack-arc-none"))));
}

/// The owned entry point (read-loop fast path) resolves the waiter from the
/// node it already owns.
#[tokio::test]
async fn ack_owned_delivery_resolves_waiter() {
    let client = crate::test_utils::create_test_client().await;

    let test_id = "ack-owned-789";
    let (tx, rx) = oneshot::channel();
    client
        .response_waiters_guard()
        .insert(test_id.to_string(), ResponseWaiter::Iq(tx));

    assert!(client.handle_ack_response_owned(owned_ack_node(test_id)));
    let received = tokio::time::timeout(Duration::from_secs(1), rx)
        .await
        .expect("waiter should resolve")
        .expect("sender must not drop");
    assert!(
        received
            .get()
            .get_attr("id")
            .is_some_and(|v| v.as_str() == test_id),
        "delivered node must carry the ack id"
    );

    assert!(!client.handle_ack_response_owned(owned_ack_node("ack-owned-none")));
}

/// Every server `<ack>` with an id dispatches an observe-only
/// `Event::ServerAck` carrying the ack's class/from/t, independent of
/// waiter state; a nack carries its error code. Lets consumers measure
/// send → server-accept latency and see nack codes programmatically
/// instead of scraping warn! logs.
#[tokio::test]
async fn test_ack_dispatches_server_ack_event() {
    use wacore::types::events::{Event, EventHandler};

    let client = crate::test_utils::create_test_client().await;
    let collector = Arc::new(crate::test_utils::TestEventCollector::default());
    client
        .subscribe_handler(collector.clone() as Arc<dyn EventHandler>)
        .detach();

    // Plain message ack (no waiter registered): event fires with the ack's
    // class, from and server timestamp; error is None.
    let ack_node = NodeBuilder::new("ack")
        .attr("id", "ack-evt-1")
        .attr("class", "message")
        .attr("from", "123456789@s.whatsapp.net")
        .attr("t", "1720000000")
        .build();
    client.handle_ack_response_arc(&Arc::new(to_owned_node(&ack_node)));
    assert!(
        collector.events().iter().any(|e| matches!(
            e.as_ref(),
            Event::ServerAck(ack)
                if ack.id == "ack-evt-1"
                    && ack.class.as_deref() == Some("message")
                    && ack.from.as_ref().is_some_and(|j| j.to_string() == "123456789@s.whatsapp.net")
                    && ack.timestamp.is_some_and(|t| t.timestamp() == 1_720_000_000)
                    && ack.error.is_none()
        )),
        "server <ack> should dispatch Event::ServerAck with class/from/t"
    );

    // Nack: the error code rides along; absent class/t stay None.
    let nack_node = NodeBuilder::new("ack")
        .attr("id", "ack-evt-2")
        .attr("error", "479")
        .attr("from", SERVER_JID)
        .build();
    client.handle_ack_response_arc(&Arc::new(to_owned_node(&nack_node)));
    assert!(
        collector.events().iter().any(|e| matches!(
            e.as_ref(),
            Event::ServerAck(ack)
                if ack.id == "ack-evt-2"
                    && ack.class.is_none()
                    && ack.timestamp.is_none()
                    && ack.error.as_deref() == Some("479")
        )),
        "server nack should dispatch Event::ServerAck carrying the error code"
    );

    // An ack without an id (e.g. non-message acks) dispatches nothing.
    let anon_ack = NodeBuilder::new("ack").attr("from", SERVER_JID).build();
    client.handle_ack_response_arc(&Arc::new(to_owned_node(&anon_ack)));
    assert_eq!(
        collector
            .events()
            .iter()
            .filter(|e| matches!(e.as_ref(), Event::ServerAck(_)))
            .count(),
        2,
        "an <ack> without an id must not dispatch Event::ServerAck"
    );

    // The headline guarantee: with a waiter registered for the same id, the
    // event STILL fires and the waiter STILL resolves — dispatch and waiter
    // resolution are independent.
    let (tx, rx) = oneshot::channel();
    client
        .response_waiters_guard()
        .insert("ack-evt-3".to_string(), ResponseWaiter::Iq(tx));
    let waited_ack = NodeBuilder::new("ack")
        .attr("id", "ack-evt-3")
        .attr("class", "message")
        .attr("from", SERVER_JID)
        .build();
    let handled = client.handle_ack_response_arc(&Arc::new(to_owned_node(&waited_ack)));
    assert!(handled, "waiter for the id should have been resolved");
    let resolved = tokio::time::timeout(Duration::from_secs(1), rx)
        .await
        .expect("timed out waiting for ack waiter")
        .expect("waiter sender was dropped");
    assert!(
        resolved
            .get()
            .get_attr("id")
            .is_some_and(|v| v.as_str() == "ack-evt-3"),
        "waiter should receive the ack node"
    );
    assert!(
        collector.events().iter().any(|e| matches!(
            e.as_ref(),
            Event::ServerAck(ack) if ack.id == "ack-evt-3"
        )),
        "Event::ServerAck should fire even when a waiter consumes the ack"
    );
}

/// Test that the lid_pn_cache correctly stores and retrieves LID mappings.
///
/// This is critical for the LID-PN session mismatch fix. When we receive a message
/// with sender_lid, we cache the phone->LID mapping so that when sending replies,
/// we can reuse the existing LID session instead of creating a new PN session.
#[tokio::test]
async fn test_lid_pn_cache_basic_operations() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_lid_cache_basic?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Initially, the cache should be empty for a phone number
    let phone = "559980000001";
    let lid = "100000012345678";

    assert!(
        client.lid_pn_cache.get_current_lid(phone).await.is_none(),
        "Cache should be empty initially"
    );

    // Insert a phone->LID mapping using add_lid_pn_mapping
    client
        .add_lid_pn_mapping(lid, phone, LearningSource::Usync)
        .await
        .expect("Failed to persist LID-PN mapping in tests");

    // Verify we can retrieve it (phone -> LID lookup)
    let cached_lid = client.lid_pn_cache.get_current_lid(phone).await;
    assert!(cached_lid.is_some(), "Cache should contain the mapping");
    assert_eq!(
        cached_lid.expect("cache should have LID"),
        lid,
        "Cached LID should match what we inserted"
    );

    // Verify reverse lookup works (LID -> phone)
    let cached_phone = client.lid_pn_cache.get_phone_number(lid).await;
    assert!(cached_phone.is_some(), "Reverse lookup should work");
    assert_eq!(
        cached_phone.expect("reverse lookup should return phone"),
        phone,
        "Cached phone should match what we inserted"
    );

    // Verify a different phone number returns None
    assert!(
        client
            .lid_pn_cache
            .get_current_lid("559980000002")
            .await
            .is_none(),
        "Different phone number should not have a mapping"
    );

    info!("✅ test_lid_pn_cache_basic_operations passed: LID-PN cache works correctly");
}

/// Test that the lid_pn_cache respects timestamp-based conflict resolution.
///
/// When a phone number has multiple LIDs, the most recent one should be returned.
#[tokio::test]
async fn test_lid_pn_cache_timestamp_resolution() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_lid_cache_timestamp?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let phone = "559980000001";
    let lid_old = "100000012345678";
    let lid_new = "100000087654321";

    // Insert initial mapping
    client
        .add_lid_pn_mapping(lid_old, phone, LearningSource::Usync)
        .await
        .expect("Failed to persist LID-PN mapping in tests");

    assert_eq!(
        client
            .lid_pn_cache
            .get_current_lid(phone)
            .await
            .expect("cache should have LID"),
        lid_old,
        "Initial LID should be stored"
    );

    // Small delay to ensure different timestamp
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Add new mapping with newer timestamp
    client
        .add_lid_pn_mapping(lid_new, phone, LearningSource::PeerPnMessage)
        .await
        .expect("Failed to persist LID-PN mapping in tests");

    assert_eq!(
        client
            .lid_pn_cache
            .get_current_lid(phone)
            .await
            .expect("cache should have newer LID"),
        lid_new,
        "Newer LID should be returned for phone lookup"
    );

    // Both LIDs should still resolve to the same phone
    assert_eq!(
        client
            .lid_pn_cache
            .get_phone_number(lid_old)
            .await
            .expect("reverse lookup should return phone"),
        phone,
        "Old LID should still map to phone"
    );
    assert_eq!(
        client
            .lid_pn_cache
            .get_phone_number(lid_new)
            .await
            .expect("reverse lookup should return phone"),
        phone,
        "New LID should also map to phone"
    );

    info!(
        "✅ test_lid_pn_cache_timestamp_resolution passed: Timestamp-based resolution works correctly"
    );
}

/// Test that get_lid_for_phone (from SendContextResolver) returns the cached value.
///
/// This is the method used by wacore::send to look up LID mappings when encrypting.
#[tokio::test]
async fn test_get_lid_for_phone_via_send_context_resolver() {
    use wacore::client::context::SendContextResolver;

    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_get_lid_for_phone?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let phone = "559980000001";
    let lid = "100000012345678";

    // Before caching, should return None
    assert!(
        client.get_lid_for_phone(phone).await.is_none(),
        "get_lid_for_phone should return None before caching"
    );

    // Cache the mapping using add_lid_pn_mapping
    client
        .add_lid_pn_mapping(lid, phone, LearningSource::Usync)
        .await
        .expect("Failed to persist LID-PN mapping in tests");

    // Now it should return the LID
    let result = client.get_lid_for_phone(phone).await;
    assert!(
        result.is_some(),
        "get_lid_for_phone should return Some after caching"
    );
    assert_eq!(
        result.expect("get_lid_for_phone should return Some"),
        lid,
        "get_lid_for_phone should return the cached LID"
    );

    info!(
        "✅ test_get_lid_for_phone_via_send_context_resolver passed: SendContextResolver correctly returns cached LID"
    );
}

/// Test that wait_for_offline_delivery_end returns immediately when the flag is already set.
#[tokio::test]
async fn test_wait_for_offline_delivery_end_returns_immediately_when_flag_set() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_offline_sync_flag_set?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Set the flag to true (simulating offline sync completed)
    client.offline_sync_completed.store(true, Ordering::Relaxed);

    // This should return immediately (not wait 10 seconds)
    let start = wacore::time::Instant::now();
    client.wait_for_offline_delivery_end().await;
    let elapsed = start.elapsed();

    // Should complete in < 100ms (not 10 second timeout)
    assert!(
        elapsed.as_millis() < 100,
        "wait_for_offline_delivery_end should return immediately when flag is set, took {:?}",
        elapsed
    );

    info!("✅ test_wait_for_offline_delivery_end_returns_immediately_when_flag_set passed");
}

/// Test that wait_for_offline_delivery_end times out when the flag is NOT set.
/// This verifies the 10-second timeout is working.
#[tokio::test]
async fn test_wait_for_offline_delivery_end_times_out_when_flag_not_set() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_offline_sync_timeout?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Flag is false by default, so use a short timeout and verify the helper
    // marks the sync complete on timeout.
    let start = wacore::time::Instant::now();
    client
        .wait_for_offline_delivery_end_with_timeout(Duration::from_millis(50))
        .await;

    let elapsed = start.elapsed();
    // The drain finisher runs as a spawned task (off the read loop) and flips
    // the flag BEFORE swapping the semaphore, so neither the flag nor the
    // notifier alone proves the swap landed. Poll until the 64-permit
    // semaphore is observable (counting by non-blocking acquire).
    let mut permits = 0;
    for _ in 0..100 {
        let semaphore = match client.message_processing_semaphore.lock() {
            Ok(guard) => guard.clone(),
            Err(poisoned) => poisoned.into_inner().clone(),
        };
        let mut guards = Vec::new();
        while let Some(guard) = semaphore.try_acquire() {
            guards.push(guard);
        }
        permits = guards.len();
        drop(guards);
        if permits == 64 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    assert!(
        elapsed.as_millis() >= 45, // Allow small timing variance
        "Should have waited for the configured timeout duration, took {:?}",
        elapsed
    );
    assert!(
        client.offline_sync_completed.load(Ordering::Relaxed),
        "wait_for_offline_delivery_end should mark offline sync complete on timeout"
    );
    assert_eq!(
        permits, 64,
        "timeout completion should restore parallel permits"
    );

    info!("✅ test_wait_for_offline_delivery_end_times_out_when_flag_not_set passed");
}

/// Test that wait_for_offline_delivery_end returns when notified.
#[tokio::test]
async fn test_wait_for_offline_delivery_end_returns_on_notify() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_offline_notify?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let client_clone = client.clone();

    // Spawn a task that will notify after 50ms
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        client_clone.offline_sync_notifier.notify(usize::MAX);
    });

    let start = wacore::time::Instant::now();
    client.wait_for_offline_delivery_end().await;
    let elapsed = start.elapsed();

    // Should complete around 50ms (when notified), not 10 seconds
    assert!(
        elapsed.as_millis() < 200,
        "wait_for_offline_delivery_end should return when notified, took {:?}",
        elapsed
    );
    assert!(
        elapsed.as_millis() >= 45, // Should have waited for the notify
        "Should have waited for the notify, only took {:?}",
        elapsed
    );

    info!("✅ test_wait_for_offline_delivery_end_returns_on_notify passed");
}

/// Test that the offline_sync_completed flag starts as false.
#[tokio::test]
async fn test_offline_sync_flag_initially_false() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_offline_flag_initial?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // The flag should be false initially
    assert!(
        !client.offline_sync_completed.load(Ordering::Relaxed),
        "offline_sync_completed should be false when Client is first created"
    );

    info!("✅ test_offline_sync_flag_initially_false passed");
}

/// Test the complete offline sync lifecycle:
/// 1. Flag starts false
/// 2. Flag is set true after IB offline stanza
/// 3. Notify is called
#[tokio::test]
async fn test_offline_sync_lifecycle() {
    use std::sync::atomic::Ordering;

    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_offline_lifecycle?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // 1. Initially false
    assert!(!client.offline_sync_completed.load(Ordering::Relaxed));

    // 2. Spawn a waiter
    let client_waiter = client.clone();
    let waiter_handle = tokio::spawn(async move {
        client_waiter.wait_for_offline_delivery_end().await;
        true // Return that we completed
    });

    // A registered listener proves the waiter reached its await point, so the
    // "still waiting" assertion below cannot pass just because the spawned task
    // never got scheduled.
    crate::test_utils::wait_for_notifier_listeners(&client.offline_sync_notifier, 1).await;

    // Verify waiter hasn't completed yet
    assert!(
        !waiter_handle.is_finished(),
        "Waiter should still be waiting"
    );

    // 3. Simulate IB handler behavior (set flag and notify)
    client.offline_sync_completed.store(true, Ordering::Relaxed);
    client.offline_sync_notifier.notify(usize::MAX);

    // 4. Waiter should complete
    let result = tokio::time::timeout(Duration::from_millis(100), waiter_handle)
        .await
        .expect("Waiter should complete after notify")
        .expect("Waiter task should not panic");

    assert!(result, "Waiter should have completed successfully");
    assert!(client.offline_sync_completed.load(Ordering::Relaxed));

    info!("✅ test_offline_sync_lifecycle passed");
}

/// Test that establish_primary_phone_session_immediate returns error when no PN is set.
/// This verifies the "not logged in" guard works.
#[tokio::test]
async fn test_establish_primary_phone_session_fails_without_pn() {
    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_no_pn?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // No PN set, so this should fail
    let result = client.establish_primary_phone_session_immediate().await;

    assert!(
        result.is_err(),
        "establish_primary_phone_session_immediate should fail when no PN is set"
    );

    let err = result.unwrap_err();
    assert!(
        err.downcast_ref::<ClientError>()
            .is_some_and(|e| matches!(e, ClientError::NotLoggedIn)),
        "Error should be ClientError::NotLoggedIn, got: {}",
        err
    );

    info!("✅ test_establish_primary_phone_session_fails_without_pn passed");
}

/// Test that ensure_e2e_sessions waits for offline sync to complete.
/// This is the CRITICAL difference between ensure_e2e_sessions and
/// establish_primary_phone_session_immediate.
#[tokio::test]
async fn test_ensure_e2e_sessions_waits_for_offline_sync() {
    use std::sync::atomic::Ordering;
    use wacore_binary::Jid;

    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_ensure_e2e_waits?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Flag is false (offline sync not complete)
    assert!(!client.offline_sync_completed.load(Ordering::Relaxed));

    // Call ensure_e2e_sessions with an empty list (so it returns early after the wait)
    // This lets us test the waiting behavior without needing network
    let client_clone = client.clone();
    let ensure_handle = tokio::spawn(async move {
        // Start with some JIDs - but since we're testing the wait, we use empty
        // to avoid needing actual session establishment
        client_clone.ensure_e2e_sessions(&[]).await
    });

    // An empty list must not wait for offline sync: the flag is still false, so a
    // waiting call would hang until DEFAULT_OFFLINE_SYNC_TIMEOUT.
    tokio::time::timeout(Duration::from_secs(5), ensure_handle)
        .await
        .expect("ensure_e2e_sessions should return immediately for empty JID list")
        .expect("ensure_e2e_sessions task should not panic")
        .expect("empty JID list should succeed");

    // Now test with actual JIDs - it should wait for offline sync
    let client_clone = client.clone();
    let test_jid = Jid::pn("559999999999");
    let ensure_handle = tokio::spawn(async move {
        // This will wait for offline sync before proceeding
        let start = wacore::time::Instant::now();
        let _ = client_clone.ensure_e2e_sessions(&[test_jid]).await;
        start.elapsed()
    });

    // Registration is what makes the assertion below scheduler-independent: it
    // pins down that `ensure_e2e_sessions` is blocked on offline sync rather than
    // simply not started yet.
    crate::test_utils::wait_for_notifier_listeners(&client.offline_sync_notifier, 1).await;

    // It should still be waiting (offline sync not complete)
    assert!(
        !ensure_handle.is_finished(),
        "ensure_e2e_sessions should be waiting for offline sync"
    );

    // Now complete offline sync
    client.offline_sync_completed.store(true, Ordering::Relaxed);
    client.offline_sync_notifier.notify(usize::MAX);

    // Now it should complete (might fail on session establishment, but that's ok)
    let result = tokio::time::timeout(Duration::from_secs(2), ensure_handle).await;

    assert!(
        result.is_ok(),
        "ensure_e2e_sessions should complete after offline sync"
    );

    info!("✅ test_ensure_e2e_sessions_waits_for_offline_sync passed");
}

/// A warm session cache must satisfy the ensure without any network fetch:
/// the client here is disconnected, so reaching the usync fetch would error.
#[tokio::test]
async fn ensure_sessions_warm_cache_short_circuits() {
    use wacore::types::jid::JidExt;
    let client = crate::test_utils::create_test_client().await;
    let jid: Jid = "15550005555@s.whatsapp.net".parse().unwrap();

    // Cold cache and disconnected: the probe misses, so the fetch runs and
    // fails — proves the pre-filter does not silently skip unknown sessions.
    assert!(
        client
            .ensure_e2e_sessions_resolved(std::slice::from_ref(&jid))
            .await
            .is_err(),
        "unknown session must still attempt the fetch"
    );

    assert!(
        client
            .signal_cache
            .try_put_session(
                &jid.to_protocol_address(),
                wacore::libsignal::protocol::SessionRecord::new_fresh(),
            )
            .is_ok()
    );
    client
        .ensure_e2e_sessions_resolved(&[jid])
        .await
        .expect("cached session must satisfy ensure without network");
}

/// Integration test: Verify that the immediate session establishment does NOT
/// wait for offline sync. This is critical for PDO to work during offline sync.
///
/// The flow is:
/// 1. Login -> establish_primary_phone_session_immediate() is called
/// 2. This should NOT wait for offline sync (flag is false at this point)
/// 3. After session is established, offline messages arrive
/// 4. When decryption fails, PDO can immediately send to device 0
#[tokio::test]
async fn test_immediate_session_does_not_wait_for_offline_sync() {
    use std::sync::atomic::Ordering;
    use wacore_binary::Jid;

    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_immediate_no_wait?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend.clone())
            .await
            .expect("persistence manager should initialize"),
    );

    // Set a PN so establish_primary_phone_session_immediate doesn't fail early
    pm.modify_device(|device| {
        device.pn = Some(Jid::pn("559999999999"));
    })
    .await;

    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Flag is false (offline sync not complete - simulating login state)
    assert!(!client.offline_sync_completed.load(Ordering::Relaxed));

    // Call establish_primary_phone_session_immediate
    // It should NOT wait for offline sync - it should proceed immediately
    let start = wacore::time::Instant::now();

    // Note: This will fail because we can't actually fetch prekeys in tests,
    // but the important thing is that it doesn't WAIT for offline sync
    let result = tokio::time::timeout(
        Duration::from_millis(500),
        client.establish_primary_phone_session_immediate(),
    )
    .await;

    let elapsed = start.elapsed();

    // The call should complete (or fail) quickly, NOT wait for 10 second timeout
    assert!(
        result.is_ok(),
        "establish_primary_phone_session_immediate should not wait for offline sync, timed out"
    );

    // It should complete in < 500ms (not 10 second wait)
    assert!(
        elapsed.as_millis() < 500,
        "establish_primary_phone_session_immediate should not wait, took {:?}",
        elapsed
    );

    // The actual result might be an error (no network), but that's fine
    // The important thing is it didn't wait for offline sync
    info!(
        "establish_primary_phone_session_immediate completed in {:?} (result: {:?})",
        elapsed,
        result.unwrap().is_ok()
    );

    info!("✅ test_immediate_session_does_not_wait_for_offline_sync passed");
}

/// Integration test: Verify that establish_primary_phone_session_immediate
/// skips establishment when a session already exists.
///
/// This is the CRITICAL fix for MAC verification failures:
/// - BUG (before fix): Called process_prekey_bundle() unconditionally,
///   replacing the existing session with a new one
/// - RESULT: Remote device still uses old session state, causing MAC failures
#[tokio::test]
async fn test_establish_session_skips_when_exists() {
    use wacore::libsignal::protocol::SessionRecord;
    use wacore::libsignal::store::SessionStore;
    use wacore::types::jid::JidExt;
    use wacore_binary::Jid;

    let backend = Arc::new(
        crate::store::SqliteStore::new("file:memdb_skip_existing?mode=memory&cache=shared")
            .await
            .expect("Failed to create in-memory backend for test"),
    );
    let pm = Arc::new(
        PersistenceManager::new(backend.clone())
            .await
            .expect("persistence manager should initialize"),
    );

    // Set a PN so the function doesn't fail early
    let own_pn = Jid::pn("559999999999");
    pm.modify_device(|device| {
        device.pn = Some(own_pn.clone());
    })
    .await;

    // Pre-populate a session for the primary phone JID (device 0)
    let primary_phone_jid = own_pn.with_device(0);
    let signal_addr = primary_phone_jid.to_protocol_address();

    // Create a dummy session record
    let dummy_session = SessionRecord::new_fresh();
    {
        let device_arc = pm.get_device_arc().await;
        let device = device_arc.read().await;
        device
            .store_session(&signal_addr, &dummy_session)
            .await
            .expect("Failed to store test session");

        // Verify session exists
        let exists = device
            .contains_session(&signal_addr)
            .await
            .expect("Failed to check session");
        assert!(exists, "Session should exist after store");
    }

    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm.clone(),
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Call establish_primary_phone_session_immediate
    // It should return Ok(()) immediately without fetching prekeys
    let result = client.establish_primary_phone_session_immediate().await;

    assert!(
        result.is_ok(),
        "establish_primary_phone_session_immediate should succeed when session exists"
    );

    // Verify the session was NOT replaced (still has the same record)
    // This is the critical assertion - if session was replaced, it would cause MAC failures
    {
        let device_arc = pm.get_device_arc().await;
        let device = device_arc.read().await;
        let exists = device
            .contains_session(&signal_addr)
            .await
            .expect("Failed to check session");
        assert!(exists, "Session should still exist after the call");
    }

    info!("✅ test_establish_session_skips_when_exists passed");
}

/// Integration test: Verify that the session check prevents MAC failures
/// by documenting the exact control flow that caused the bug.
#[test]
fn test_mac_failure_prevention_flow_documentation() {
    // Simulate the decision logic
    fn should_establish_session(check_result: Result<bool, &'static str>) -> Result<bool, String> {
        match check_result {
            Ok(true) => Ok(false), // Session exists → DON'T establish
            Ok(false) => Ok(true), // No session → establish
            Err(e) => Err(format!("Cannot verify session: {}", e)), // Fail-safe
        }
    }

    // Test Case 1: Session exists → skip (prevents MAC failure)
    let result = should_establish_session(Ok(true));
    assert_eq!(result, Ok(false), "Should skip when session exists");

    // Test Case 2: No session → establish
    let result = should_establish_session(Ok(false));
    assert_eq!(result, Ok(true), "Should establish when no session");

    // Test Case 3: Check fails → error (fail-safe)
    let result = should_establish_session(Err("database error"));
    assert!(result.is_err(), "Should fail when check fails");

    info!("✅ test_mac_failure_prevention_flow_documentation passed");
}

#[test]
fn test_unified_session_id_calculation() {
    // Test the mathematical calculation of the unified session ID.
    // Formula: (now_ms + server_offset_ms + 3_days_ms) % 7_days_ms

    const DAY_MS: i64 = 24 * 60 * 60 * 1000;
    const WEEK_MS: i64 = 7 * DAY_MS;
    const OFFSET_MS: i64 = 3 * DAY_MS;

    // Helper function matching the implementation
    fn calculate_session_id(now_ms: i64, server_offset_ms: i64) -> i64 {
        let adjusted_now = now_ms + server_offset_ms;
        (adjusted_now + OFFSET_MS) % WEEK_MS
    }

    // Test 1: Zero offset
    let now_ms = 1706000000000_i64; // Some arbitrary timestamp
    let id = calculate_session_id(now_ms, 0);
    assert!(
        (0..WEEK_MS).contains(&id),
        "Session ID should be in [0, WEEK_MS)"
    );

    // Test 2: Positive server offset (server is ahead)
    let id_with_positive_offset = calculate_session_id(now_ms, 5000);
    assert!(
        (0..WEEK_MS).contains(&id_with_positive_offset),
        "Session ID should be in [0, WEEK_MS)"
    );
    // The ID should be different from zero offset (unless wrap-around)
    // Not testing exact value as it depends on the offset

    // Test 3: Negative server offset (server is behind)
    let id_with_negative_offset = calculate_session_id(now_ms, -5000);
    assert!(
        (0..WEEK_MS).contains(&id_with_negative_offset),
        "Session ID should be in [0, WEEK_MS)"
    );

    // Test 4: Verify modulo wrap-around
    // If adjusted_now + OFFSET_MS >= WEEK_MS, it should wrap
    let wrap_test_now = WEEK_MS - OFFSET_MS + 1000; // Should produce small result
    let wrapped_id = calculate_session_id(wrap_test_now, 0);
    assert_eq!(wrapped_id, 1000, "Should wrap around correctly");

    // Test 5: Edge case - at exact boundary
    let boundary_now = WEEK_MS - OFFSET_MS;
    let boundary_id = calculate_session_id(boundary_now, 0);
    assert_eq!(boundary_id, 0, "At exact boundary should be 0");
}

#[tokio::test]
async fn test_server_time_offset_extraction() {
    use wacore_binary::builder::NodeBuilder;

    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Initially, offset should be 0
    assert_eq!(
        client.unified_session.server_time_offset_ms(),
        0,
        "Initial offset should be 0"
    );

    // Create a node with a 't' attribute
    let server_time = wacore::time::now_secs() + 10; // Server is 10 seconds ahead
    let node = NodeBuilder::new("success").attr("t", server_time).build();

    // Update the offset
    client.update_server_time_offset(&node.as_node_ref());

    // The offset should be approximately 10 * 1000 = 10000 ms
    // Allow some tolerance for timing differences during the test
    let offset = client.unified_session.server_time_offset_ms();
    assert!(
        (offset - 10000).abs() < 1000, // Allow 1 second tolerance
        "Offset should be approximately 10000ms, got {}",
        offset
    );

    // Test with no 't' attribute - should not change offset
    let node_no_t = NodeBuilder::new("success").build();
    client.update_server_time_offset(&node_no_t.as_node_ref());
    let offset_after = client.unified_session.server_time_offset_ms();
    assert!(
        (offset_after - offset).abs() < 100, // Should be same (or very close)
        "Offset should not change when 't' is missing"
    );

    // Test with invalid 't' attribute - should not change offset
    let node_invalid = NodeBuilder::new("success")
        .attr("t", "not_a_number")
        .build();
    client.update_server_time_offset(&node_invalid.as_node_ref());
    let offset_after_invalid = client.unified_session.server_time_offset_ms();
    assert!(
        (offset_after_invalid - offset).abs() < 100,
        "Offset should not change when 't' is invalid"
    );

    // Test with negative/zero 't' - should not change offset
    let node_zero = NodeBuilder::new("success").attr("t", "0").build();
    client.update_server_time_offset(&node_zero.as_node_ref());
    let offset_after_zero = client.unified_session.server_time_offset_ms();
    assert!(
        (offset_after_zero - offset).abs() < 100,
        "Offset should not change when 't' is 0"
    );

    info!("✅ test_server_time_offset_extraction passed");
}

#[tokio::test]
async fn test_unified_session_manager_integration() {
    // Test the unified session manager through the client

    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Initially, sequence should be 0
    assert_eq!(
        client.unified_session.sequence(),
        0,
        "Initial sequence should be 0"
    );

    // Duplicate prevention depends on the session ID staying the same between calls.
    // Since the session ID is millisecond-based, use a retry loop to handle
    // the rare case where we cross a millisecond boundary between calls.
    loop {
        client.unified_session.reset().await;

        let result = client.unified_session.prepare_send().await;
        assert!(result.is_some(), "First send should succeed");
        let (node, seq) = result.unwrap();
        assert_eq!(node.tag, "ib", "Should be an IB stanza");
        assert_eq!(seq, 1, "First sequence should be 1 (pre-increment)");
        assert_eq!(client.unified_session.sequence(), 1);

        let result2 = client.unified_session.prepare_send().await;
        if result2.is_none() {
            // Duplicate was prevented within the same millisecond
            assert_eq!(client.unified_session.sequence(), 1);
            break;
        }
        // Millisecond boundary crossed, retry
        tokio::task::yield_now().await;
    }

    // Clear last sent and try again - sequence resets on "new" session ID
    client.unified_session.clear_last_sent().await;
    let result3 = client.unified_session.prepare_send().await;
    assert!(result3.is_some(), "Should succeed after clearing");
    let (_, seq3) = result3.unwrap();
    assert_eq!(seq3, 1, "Sequence resets when session ID changes");
    assert_eq!(client.unified_session.sequence(), 1);

    info!("✅ test_unified_session_manager_integration passed");
}

#[test]
fn test_unified_session_protocol_node() {
    // Test the type-safe protocol node implementation
    use wacore::ib::{IbStanza, UnifiedSession};
    use wacore::protocol::ProtocolNode;

    // Create a unified session
    let session = UnifiedSession::new("123456789");
    assert_eq!(session.id, "123456789");
    assert_eq!(session.tag(), "unified_session");

    // Convert to node
    let node = session.into_node();
    assert_eq!(node.tag, "unified_session");
    assert!(node.attrs.get("id").is_some_and(|v| v == "123456789"));

    // Create an IB stanza
    let stanza = IbStanza::unified_session(UnifiedSession::new("987654321"));
    assert_eq!(stanza.tag(), "ib");

    // Convert to node and verify structure
    let ib_node = stanza.into_node();
    assert_eq!(ib_node.tag, "ib");
    let children = ib_node.children().expect("IB stanza should have children");
    assert_eq!(children.len(), 1);
    assert_eq!(children[0].tag, "unified_session");
    assert!(
        children[0]
            .attrs
            .get("id")
            .is_some_and(|v| v == "987654321")
    );

    info!("✅ test_unified_session_protocol_node passed");
}

fn node_to_owned_ref(node: Node) -> Arc<wacore_binary::OwnedNodeRef> {
    crate::test_utils::node_to_owned_ref(&node)
}

/// Helper to create a test client for offline sync tests
async fn create_offline_sync_test_client() -> Arc<Client> {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;
    client
}

/// Regression: a transport disconnect must flush dirty Signal state before
/// clearing the cache, or a just-advanced sender-key chain is lost (forcing
/// a full SKDM re-fanout on the next send).
#[tokio::test]
async fn cleanup_connection_state_flushes_dirty_signal_state() {
    use wacore::libsignal::protocol::ProtocolAddress;
    let client = create_offline_sync_test_client().await;

    // A dirty identity lives only in the write-back cache until flushed.
    let addr = ProtocolAddress::new("5550001000@s.whatsapp.net", 1u32.into());
    client.signal_cache.put_identity(&addr, &[7u8; 32]).await;

    client.cleanup_connection_state().await;

    // cleanup cleared the cache, so a hit now can only come from the DB,
    // proving the flush ran before the clear.
    let device = client.persistence_manager.get_device_arc().await;
    let guard = device.read().await;
    let persisted = client
        .signal_cache
        .get_identity(&addr, &*guard.backend)
        .await
        .expect("get_identity must not error");
    assert!(
        persisted.is_some(),
        "dirty Signal state must survive a transport disconnect (flush-before-clear)"
    );
}

/// Same guarantee on the sender-key store, which drives SKDM fanout.
#[tokio::test]
async fn cleanup_connection_state_flushes_dirty_sender_key() {
    use wacore::libsignal::protocol::SenderKeyRecord;
    use wacore::libsignal::store::sender_key_name::SenderKeyName;
    let client = create_offline_sync_test_client().await;

    let name = SenderKeyName::from_parts("group@g.us", "5550001000@s.whatsapp.net:1");
    client
        .signal_cache
        .put_sender_key(&name, SenderKeyRecord::new_empty())
        .await;

    client.cleanup_connection_state().await;

    let device = client.persistence_manager.get_device_arc().await;
    let guard = device.read().await;
    let persisted = client
        .signal_cache
        .get_sender_key(&name, &*guard.backend)
        .await
        .expect("get_sender_key must not error");
    assert!(
        persisted.is_some(),
        "dirty sender key must survive a transport disconnect (flush-before-clear)"
    );
}

#[tokio::test]
async fn cleanup_connection_state_does_not_burn_a_clean_sender_key_lease() {
    use wacore::libsignal::protocol::{KeyPair, SenderKeyRecord};
    use wacore::libsignal::store::sender_key_name::SenderKeyName;
    let client = create_offline_sync_test_client().await;
    let name = SenderKeyName::from_parts("group@g.us", "5550001001@s.whatsapp.net:1");
    let mut rng = rand::make_rng::<rand::rngs::StdRng>();
    let signing_key = KeyPair::generate(&mut rng);
    let mut record = SenderKeyRecord::new_empty();
    record
        .add_sender_key_state(
            3,
            12345,
            0,
            &[0x42; 32],
            signing_key.public_key,
            Some(signing_key.private_key),
        )
        .expect("sender key state");
    record.reserve_iterations(0);
    client.signal_cache.put_sender_key(&name, record).await;

    client.cleanup_connection_state().await;

    let device = client.persistence_manager.get_device_arc().await;
    let guard = device.read().await;
    let reloaded = client
        .signal_cache
        .get_sender_key(&name, &*guard.backend)
        .await
        .expect("sender key load")
        .expect("sender key");
    assert_eq!(
        reloaded
            .sender_key_state()
            .expect("sender key state")
            .sender_chain_key()
            .expect("sender chain")
            .iteration(),
        0
    );
}

/// When the flush itself fails, cleanup must NOT clear the cache, or it would
/// drop the very state the flush was meant to persist.
#[tokio::test]
async fn cleanup_connection_state_keeps_state_when_flush_fails() {
    use wacore::libsignal::protocol::{ProtocolAddress, SenderKeyRecord};
    use wacore::libsignal::store::sender_key_name::SenderKeyName;
    let client = create_offline_sync_test_client().await;

    // A malformed identity (not 32 bytes) makes flush() error out, standing
    // in for a transient backend write failure during cleanup.
    let bad = ProtocolAddress::new("5550002000@s.whatsapp.net", 1u32.into());
    client.signal_cache.put_identity(&bad, &[0u8; 16]).await;

    // A valid dirty sender key that must not be dropped when the flush fails.
    let name = SenderKeyName::from_parts("group@g.us", "5550001000@s.whatsapp.net:1");
    client
        .signal_cache
        .put_sender_key(&name, SenderKeyRecord::new_empty())
        .await;

    client.cleanup_connection_state().await;

    // flush() failed, so clear() was skipped; the unpersisted sender key
    // survives in the write-back cache instead of being dropped.
    let device = client.persistence_manager.get_device_arc().await;
    let guard = device.read().await;
    let persisted = client
        .signal_cache
        .get_sender_key(&name, &*guard.backend)
        .await
        .expect("get_sender_key must not error");
    assert!(
        persisted.is_some(),
        "a flush failure must not drop dirty Signal state"
    );
}

/// A 403 connect failure is WA Web's REASON_LOCKED: it must surface a logout
/// carrying AccountLocked and disable auto-reconnect (a lock is not transient).
#[tokio::test]
async fn connect_failure_403_dispatches_account_locked_logout() {
    use wacore::types::events::ChannelEventHandler;
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    // location="rva" is a region routing token and must not change the verdict.
    let failure = NodeBuilder::new("failure")
        .attr("reason", "403")
        .attr("location", "rva")
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    let evt = events
        .try_recv()
        .expect("403 must dispatch a LoggedOut event");
    match &*evt {
        Event::LoggedOut(lo) => {
            assert!(lo.on_connect, "403 arrives as a failure-on-connect");
            assert_eq!(lo.reason, ConnectFailureReason::AccountLocked);
        }
        _ => panic!("expected Event::LoggedOut for reason=403"),
    }
    assert!(
        !client.enable_auto_reconnect.load(Ordering::Relaxed),
        "a server-side lock must not auto-reconnect"
    );
}

/// An account lock states its enforcement data exactly once: the appeal token is
/// the only route to contest the lock, and `violation_reason` / `vt` are the
/// only description of it. WA Web ignores those attributes (its appeal flow is
/// native), so nothing parses them here either — but dropping them makes them
/// unrecoverable, so the whole stanza rides on the event.
#[tokio::test]
async fn account_lock_logout_preserves_enforcement_attributes() {
    use wacore::types::events::ChannelEventHandler;
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    let failure = NodeBuilder::new("failure")
        .attr("reason", "403")
        .attr("location", "rva")
        .attr("violation_reason", "other_harm")
        .attr("vt", "1")
        .attr("appeal_token", "0aFICTITIOUSappealTOKEN00")
        .attr("logout_message_header", "Conta desconectada")
        .attr("logout_message_subtext", "Abra o WhatsApp no celular")
        .attr("logout_message_locale", "pt_BR")
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    let evt = events.try_recv().expect("403 dispatches LoggedOut");
    match &*evt {
        Event::LoggedOut(lo) => {
            let raw = lo.raw.as_ref().expect("the <failure> stanza must survive");
            assert_eq!(
                raw.attrs.get("appeal_token").map(|v| v.as_str()).as_deref(),
                Some("0aFICTITIOUSappealTOKEN00"),
                "the one-time appeal token must reach the embedder"
            );
            assert_eq!(
                raw.attrs
                    .get("violation_reason")
                    .map(|v| v.as_str())
                    .as_deref(),
                Some("other_harm")
            );
            assert_eq!(
                raw.attrs.get("vt").map(|v| v.as_str()).as_deref(),
                Some("1")
            );

            // The localized copy is typed, the way WA Web parses it, with the
            // locale that decides whether it is safe to render.
            let msg = lo
                .logout_message
                .as_ref()
                .expect("logout_message_* must be surfaced");
            assert_eq!(msg.header.as_deref(), Some("Conta desconectada"));
            assert_eq!(msg.subtext.as_deref(), Some("Abra o WhatsApp no celular"));
            assert_eq!(msg.locale.as_deref(), Some("pt_BR"));
        }
        _ => panic!("expected Event::LoggedOut for reason=403"),
    }
}

/// WA Web hands `code`, `expire`, `message` and `url` to its temporary-ban UI —
/// `url` is the link it opens. All four must survive the dispatch.
#[tokio::test]
async fn temporary_ban_carries_message_url_and_stanza() {
    use wacore::types::events::{ChannelEventHandler, TempBanReason};
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    let failure = NodeBuilder::new("failure")
        .attr("reason", "402")
        .attr("code", "101")
        .attr("expire", "3600")
        .attr("message", "too many messages")
        .attr("url", "https://faq.example.invalid/ban")
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    match &*events.try_recv().expect("402 dispatches TemporaryBan") {
        Event::TemporaryBan(ban) => {
            assert_eq!(ban.code, TempBanReason::SentToTooManyPeople);
            assert_eq!(ban.expire, chrono::Duration::seconds(3600));
            assert_eq!(ban.message.as_deref(), Some("too many messages"));
            assert_eq!(ban.url.as_deref(), Some("https://faq.example.invalid/ban"));
            assert!(ban.raw.is_some(), "the <failure> stanza must survive");
        }
        _ => panic!("expected Event::TemporaryBan for reason=402"),
    }
}

/// A 402 without `expire` is not a ban that lifted at the epoch. WA Web errors
/// out rather than reporting one, so we surface the raw failure instead of
/// fabricating a zero duration.
#[tokio::test]
async fn temporary_ban_without_expire_falls_back_to_connect_failure() {
    use wacore::types::events::ChannelEventHandler;
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    let failure = NodeBuilder::new("failure")
        .attr("reason", "402")
        .attr("code", "101")
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    match &*events
        .try_recv()
        .expect("an incomplete 402 still dispatches")
    {
        Event::ConnectFailure(cf) => {
            assert_eq!(cf.reason, ConnectFailureReason::TempBanned);
            assert!(cf.raw.is_some(), "the <failure> stanza must survive");
        }
        other => panic!("expected Event::ConnectFailure, got {other:?}"),
    }
}

/// An `expire` that cannot be a `Duration` is no better than a missing one: it
/// must not reach a consumer as a ban of length zero.
#[tokio::test]
async fn temporary_ban_with_unrepresentable_expire_falls_back_to_connect_failure() {
    use wacore::types::events::ChannelEventHandler;
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    let failure = NodeBuilder::new("failure")
        .attr("reason", "402")
        .attr("code", "101")
        .attr("expire", u64::MAX.to_string())
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    match &*events.try_recv().expect("a garbage 402 still dispatches") {
        Event::ConnectFailure(cf) => {
            assert_eq!(cf.reason, ConnectFailureReason::TempBanned);
            assert!(cf.raw.is_some(), "the <failure> stanza must survive");
        }
        other => panic!("expected Event::ConnectFailure, got {other:?}"),
    }
}

/// 405 is the one branch with nothing to parse, which is exactly why it used to
/// throw the stanza away; the client version the server rejected is in there.
#[tokio::test]
async fn client_outdated_carries_the_stanza() {
    use wacore::types::events::ChannelEventHandler;
    let client = create_offline_sync_test_client().await;
    let (handler, events) = ChannelEventHandler::new();
    client.subscribe_handler(handler).detach();

    let failure = NodeBuilder::new("failure")
        .attr("reason", "405")
        .attr("message", "client too old")
        .build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    match &*events.try_recv().expect("405 dispatches ClientOutdated") {
        Event::ClientOutdated(co) => {
            assert!(co.raw.is_some(), "the <failure> stanza must survive")
        }
        _ => panic!("expected Event::ClientOutdated for reason=405"),
    }
}

#[tokio::test]
async fn delivery_receipt_activity_state_machine() {
    let client = create_offline_sync_test_client().await;
    assert!(
        !client.receipts_are_active(),
        "default is inactive (background companion)"
    );
    client.mark_receipts_active_on_presence();
    assert!(client.receipts_are_active(), "presence available -> active");
    client.mark_receipts_inactive_on_presence();
    assert!(
        !client.receipts_are_active(),
        "presence unavailable -> inactive"
    );
    client.set_force_active_delivery_receipts(true);
    assert!(client.receipts_are_active(), "forced active");
    client.mark_receipts_inactive_on_presence();
    assert!(
        client.receipts_are_active(),
        "forced (2) survives a presence-unavailable CAS(1,0)"
    );
    client.set_force_active_delivery_receipts(false);
    assert!(!client.receipts_are_active());

    // Teardown resets presence-driven active (so it doesn't leak across
    // reconnects) but preserves a forced value.
    client.mark_receipts_active_on_presence();
    client.cleanup_connection_state().await;
    assert!(
        !client.receipts_are_active(),
        "teardown resets presence-driven active"
    );
    client.set_force_active_delivery_receipts(true);
    client.cleanup_connection_state().await;
    assert!(
        client.receipts_are_active(),
        "teardown preserves forced active"
    );
}

#[tokio::test]
async fn test_ib_thread_metadata_does_not_end_sync() {
    let client = create_offline_sync_test_client().await;
    client
        .offline_sync_metrics
        .active
        .store(true, Ordering::Release);

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("thread_metadata")
            .children([NodeBuilder::new("item").build()])
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert!(
        client.offline_sync_metrics.active.load(Ordering::Acquire),
        "<ib><thread_metadata> should NOT end offline sync"
    );
}

#[tokio::test]
async fn test_ib_edge_routing_does_not_end_sync() {
    let client = create_offline_sync_test_client().await;
    client
        .offline_sync_metrics
        .active
        .store(true, Ordering::Release);

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("edge_routing")
            .children([NodeBuilder::new("routing_info")
                .bytes(vec![1, 2, 3])
                .build()])
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert!(
        client.offline_sync_metrics.active.load(Ordering::Acquire),
        "<ib><edge_routing> should NOT end offline sync"
    );
}

#[tokio::test]
async fn test_ib_dirty_does_not_end_sync() {
    let client = create_offline_sync_test_client().await;
    client
        .offline_sync_metrics
        .active
        .store(true, Ordering::Release);

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("dirty")
            .attr("type", "groups")
            .attr("timestamp", "1234")
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert!(
        client.offline_sync_metrics.active.load(Ordering::Acquire),
        "<ib><dirty> should NOT end offline sync"
    );
}

#[tokio::test]
async fn test_ib_offline_child_ends_sync() {
    let client = create_offline_sync_test_client().await;
    client
        .offline_sync_metrics
        .active
        .store(true, Ordering::Release);
    client
        .offline_sync_metrics
        .total_messages
        .store(301, Ordering::Release);

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("offline").attr("count", "301").build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert!(
        !client.offline_sync_metrics.active.load(Ordering::Acquire),
        "<ib><offline count='301'/> should end offline sync"
    );
}

#[tokio::test]
async fn test_ib_offline_preview_starts_sync() {
    let client = create_offline_sync_test_client().await;

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("offline_preview")
            .attr("count", "301")
            .attr("message", "168")
            .attr("notification", "62")
            .attr("receipt", "68")
            .attr("appdata", "0")
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert!(
        client.offline_sync_metrics.active.load(Ordering::Acquire),
        "offline_preview with count>0 should activate sync"
    );
    assert_eq!(
        client
            .offline_sync_metrics
            .total_messages
            .load(Ordering::Acquire),
        301
    );
}

#[tokio::test]
async fn test_offline_message_increments_processed() {
    let client = create_offline_sync_test_client().await;
    client
        .offline_sync_metrics
        .active
        .store(true, Ordering::Release);
    client
        .offline_sync_metrics
        .total_messages
        .store(100, Ordering::Release);

    let node = NodeBuilder::new("message")
        .attr("offline", "1")
        .attr("from", "5551234567@s.whatsapp.net")
        .attr("id", "TEST123")
        .attr("t", "1772884671")
        .attr("type", "text")
        .build();

    client.process_node(node_to_owned_ref(node)).await;
    assert_eq!(
        client
            .offline_sync_metrics
            .processed_messages
            .load(Ordering::Acquire),
        1,
        "offline message should increment processed count"
    );
}

// ---------------------------------------------------------------
// Server-initiated ping detection tests
//
// The WhatsApp server can send pings in two formats:
//
// 1. Child-element format (legacy/whatsmeow style):
//    <iq type="get" from="s.whatsapp.net" id="...">
//      <ping/>
//    </iq>
//
// 2. xmlns-attribute format (real WhatsApp Web format):
//    <iq from="s.whatsapp.net" t="..." type="get" xmlns="urn:xmpp:ping"/>
//    This is a self-closing tag with NO child elements.
//    Verified against captured WhatsApp Web JS (WAWebCommsHandleStanza):
//      if (t.xmlns === "urn:xmpp:ping") return wap("iq", { type: "result", to: t.from });
//
// Both must be recognized and answered with a pong, otherwise the
// server considers the client dead and stops responding to keepalive
// pings — causing a timeout cascade and forced reconnect.
// ---------------------------------------------------------------

#[tokio::test]
async fn test_handle_iq_ping_with_child_element() {
    // Format 1: <iq type="get"><ping/></iq> — the legacy format with a <ping> child node.
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let ping_node = NodeBuilder::new("iq")
        .attr("type", "get")
        .attr("from", SERVER_JID)
        .attr("id", "ping-child-1")
        .children([NodeBuilder::new("ping").build()])
        .build();

    let handled = client.handle_iq(&ping_node.as_node_ref()).await;
    assert!(
        handled,
        "handle_iq must recognize ping with <ping> child element"
    );
}

#[tokio::test]
async fn test_handle_iq_ping_with_xmlns_attribute() {
    // Format 2: <iq type="get" xmlns="urn:xmpp:ping"/> — the real WhatsApp Web format.
    // This is a self-closing IQ with NO children, only an xmlns attribute.
    // The server sends this format; failing to respond causes keepalive timeout cascade.
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let ping_node = NodeBuilder::new("iq")
        .attr("type", "get")
        .attr("from", SERVER_JID)
        .attr("id", "ping-xmlns-1")
        .attr("xmlns", "urn:xmpp:ping")
        .build();

    let handled = client.handle_iq(&ping_node.as_node_ref()).await;
    assert!(
        handled,
        "handle_iq must recognize ping with xmlns=\"urn:xmpp:ping\" attribute (no children)"
    );
}

#[tokio::test]
async fn test_handle_iq_ping_with_both_child_and_xmlns() {
    // Edge case: node has BOTH a <ping> child AND xmlns="urn:xmpp:ping".
    // Should still be handled (OR condition).
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let ping_node = NodeBuilder::new("iq")
        .attr("type", "get")
        .attr("from", SERVER_JID)
        .attr("id", "ping-both-1")
        .attr("xmlns", "urn:xmpp:ping")
        .children([NodeBuilder::new("ping").build()])
        .build();

    let handled = client.handle_iq(&ping_node.as_node_ref()).await;
    assert!(
        handled,
        "handle_iq must handle ping with both child and xmlns"
    );
}

#[tokio::test]
async fn test_handle_iq_ping_without_type_attr() {
    // WA Web pongs for any xmlns="urn:xmpp:ping" regardless of (or absent) type.
    // A ping with no type attr must still be answered, not dropped.
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let ping_node = NodeBuilder::new("iq")
        .attr("from", SERVER_JID)
        .attr("id", "ping-notype-1")
        .attr("xmlns", "urn:xmpp:ping")
        .build();

    let handled = client.handle_iq(&ping_node.as_node_ref()).await;
    assert!(
        handled,
        "handle_iq must pong a urn:xmpp:ping IQ even without a type attribute"
    );
}

#[tokio::test]
async fn test_handle_iq_non_ping_returns_false() {
    // A type="get" IQ without ping child or xmlns should NOT be handled as ping.
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let non_ping_node = NodeBuilder::new("iq")
        .attr("type", "get")
        .attr("from", SERVER_JID)
        .attr("id", "not-a-ping")
        .attr("xmlns", "some:other:namespace")
        .build();

    let handled = client.handle_iq(&non_ping_node.as_node_ref()).await;
    assert!(
        !handled,
        "handle_iq must NOT treat non-ping xmlns as a ping"
    );
}

#[tokio::test]
async fn test_handle_iq_ping_wrong_type_returns_false() {
    // xmlns="urn:xmpp:ping" but type="result" (not "get") — should NOT be handled as ping.
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    let result_node = NodeBuilder::new("iq")
        .attr("type", "result")
        .attr("from", SERVER_JID)
        .attr("id", "ping-result-1")
        .attr("xmlns", "urn:xmpp:ping")
        .build();

    let handled = client.handle_iq(&result_node.as_node_ref()).await;
    assert!(
        !handled,
        "handle_iq must NOT respond to type=\"result\" even with ping xmlns"
    );
}

// ── build_pong tests ──────────────────────────────────────────────

#[test]
fn test_build_pong_with_id() {
    let pong = build_pong("s.whatsapp.net".to_string(), Some("ping-123"));
    assert!(
        pong.attrs.get("id").is_some_and(|v| v == "ping-123"),
        "pong should include id when server ping has one"
    );
    assert!(pong.attrs.get("type").is_some_and(|v| v == "result"));
    assert!(pong.attrs.get("to").is_some_and(|v| v == "s.whatsapp.net"));
}

#[test]
fn test_build_pong_without_id() {
    let pong = build_pong("s.whatsapp.net".to_string(), None);
    assert!(
        !pong.attrs.contains_key("id"),
        "pong should NOT include id when server ping has none"
    );
    assert!(pong.attrs.get("type").is_some_and(|v| v == "result"));
}

#[test]
fn test_encrypt_identity_notification_omits_type() {
    let node = NodeBuilder::new("notification")
        .attr("from", "186303081611421@lid")
        .attr("id", "4128735301")
        .attr("type", "encrypt")
        .children([NodeBuilder::new("identity").build()])
        .build();

    assert!(
        is_encrypt_identity_notification(&node.as_node_ref()),
        "identity-change notification ACK must omit type to match WA Web"
    );
}

#[test]
fn test_device_notification_is_not_encrypt_identity() {
    let node = NodeBuilder::new("notification")
        .attr("from", "186303081611421@lid")
        .attr("id", "269488578")
        .attr("type", "devices")
        .children([NodeBuilder::new("remove").build()])
        .build();

    assert!(
        !is_encrypt_identity_notification(&node.as_node_ref()),
        "device notification is not an encrypt+identity notification"
    );
}

#[test]
fn test_build_ack_node_for_message_preserves_type_and_includes_from() {
    // Generic message acknowledgements echo the stanza type and identify the
    // local device in `from`.
    let incoming = NodeBuilder::new("message")
        .attr("from", "120363161500776365@g.us")
        .attr("id", "A5791A5392EF60E3FB0670098DE010D4")
        .attr("type", "text")
        .attr("participant", "181531758878822@lid")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("message ack should be buildable");

    assert_eq!(ack.tag, "ack");
    // Use PartialEq<str> on NodeValue — works for both String and Jid variants
    // without allocation, so tests don't depend on internal representation.
    assert!(ack.attrs.get("class").is_some_and(|v| v == "message"));
    assert!(
        ack.attrs
            .get("to")
            .is_some_and(|v| v == "120363161500776365@g.us")
    );
    assert!(
        ack.attrs
            .get("from")
            .is_some_and(|v| v == "155500012345:48@s.whatsapp.net")
    );
    assert!(
        ack.attrs
            .get("participant")
            .is_some_and(|v| v == "181531758878822@lid")
    );
    assert!(
        ack.attrs.get("type").is_some_and(|v| v == "text"),
        "message ACK must echo its explicit type"
    );
}

#[test]
fn test_build_ack_node_for_identity_change_omits_type_and_from() {
    let incoming = NodeBuilder::new("notification")
        .attr("from", "186303081611421@lid")
        .attr("id", "4128735301")
        .attr("type", "encrypt")
        .children([NodeBuilder::new("identity").build()])
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("notification ack should be buildable");

    assert!(ack.attrs.get("class").is_some_and(|v| v == "notification"));
    assert!(
        !ack.attrs.contains_key("type"),
        "identity-change notification ACK must omit type"
    );
    assert!(
        !ack.attrs.contains_key("from"),
        "notification ACKs should not include our device PN"
    );
}

#[test]
fn test_build_ack_node_for_receipt_with_type_echoes_type() {
    // Receipt acks should echo the type attribute when present (e.g. "read", "played").
    let incoming = NodeBuilder::new("receipt")
        .attr("from", "156535032389744@lid")
        .attr("id", "RCPT-WITH-TYPE")
        .attr("type", "read")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("receipt ack should be buildable");

    assert!(ack.attrs.get("class").is_some_and(|v| v == "receipt"));
    assert!(
        ack.attrs.get("type").is_some_and(|v| v == "read"),
        "receipt ACK must echo the type attribute when present"
    );
    assert!(
        !ack.attrs.contains_key("from"),
        "receipt ACKs should not include our device PN"
    );
}

#[test]
fn test_build_ack_node_drops_participant_when_equal_to_from() {
    // WAWebReceiptAck: `participant: r && r !== e ? DEVICE_JID(r) : DROP_ATTR`.
    // When the incoming stanza carries participant == from (redundant),
    // the ack must not echo it.
    let incoming = NodeBuilder::new("receipt")
        .attr("from", "156535032389744@lid")
        .attr("participant", "156535032389744@lid")
        .attr("id", "RCPT-PARTICIPANT-EQ-FROM")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net".parse().unwrap();

    let ack =
        build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn)).expect("ack should build");
    assert!(
        !ack.attrs.contains_key("participant"),
        "ack must drop participant when it duplicates `to` (the flipped from); got {:?}",
        ack.attrs.get("participant")
    );
}

#[test]
fn test_build_ack_node_keeps_participant_when_distinct_from_from() {
    // Group receipt: participant = sender (user), from = group jid; must be kept.
    let incoming = NodeBuilder::new("receipt")
        .attr("from", "120363098765432100@g.us")
        .attr("participant", "5511999999999@s.whatsapp.net")
        .attr("id", "RCPT-GROUP")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net".parse().unwrap();

    let ack =
        build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn)).expect("ack should build");
    assert!(
        ack.attrs
            .get("participant")
            .is_some_and(|v| v == "5511999999999@s.whatsapp.net"),
        "ack must keep participant when it differs from `to`"
    );
}

#[test]
fn test_build_ack_node_for_receipt_without_type_omits_type() {
    // Delivery receipts have no type attribute — the ack must also omit it.
    // Sending type="delivery" in the ack causes stream:error disconnections.
    let incoming = NodeBuilder::new("receipt")
        .attr("from", "156535032389744@lid")
        .attr("id", "RCPT-NO-TYPE")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("receipt ack should be buildable");

    assert!(ack.attrs.get("class").is_some_and(|v| v == "receipt"));
    assert!(
        !ack.attrs.contains_key("type"),
        "receipt ACK must NOT contain type when the incoming receipt has no type attribute"
    );
    assert!(
        !ack.attrs.contains_key("from"),
        "receipt ACKs should not include our device PN"
    );
}

#[test]
fn test_build_ack_node_for_message_with_recipient_preserves_recipient() {
    // Peer / hosted-companion / LID-routed messages carry `recipient`.
    // The server uses it to route the ack back to the origin device;
    // without it the stream is torn down with <stream:error><ack/></stream:error>.
    let incoming = NodeBuilder::new("message")
        .attr("from", "166361967902821@lid")
        .attr("id", "2A32F960553696093D99")
        .attr("type", "text")
        .attr("recipient", "146991363395800@lid")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("message ack should be buildable");

    assert!(ack.attrs.get("class").is_some_and(|v| v == "message"));
    assert!(
        ack.attrs
            .get("recipient")
            .is_some_and(|v| v == "146991363395800@lid"),
        "message ACK must echo the incoming `recipient` attribute"
    );
}

#[test]
fn test_build_ack_node_for_receipt_with_recipient_preserves_recipient() {
    // Receipt acks must also echo `recipient` when the incoming carries it.
    let incoming = NodeBuilder::new("receipt")
        .attr("from", "120363098765432100@g.us")
        .attr("id", "RCPT-WITH-RECIPIENT")
        .attr("type", "read")
        .attr("recipient", "242395589390497@lid")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("receipt ack should be buildable");

    assert!(ack.attrs.get("class").is_some_and(|v| v == "receipt"));
    assert!(
        ack.attrs
            .get("recipient")
            .is_some_and(|v| v == "242395589390497@lid"),
        "receipt ACK must echo the incoming `recipient` attribute"
    );
}

#[test]
fn test_build_ack_node_for_message_without_recipient_omits_recipient() {
    // Regression guard: never synthesise a `recipient` field if the
    // incoming stanza did not carry one — server would reject the ack.
    let incoming = NodeBuilder::new("message")
        .attr("from", "120363161500776365@g.us")
        .attr("id", "A5791A5392EF60E3FB06")
        .attr("type", "text")
        .attr("participant", "181531758878822@lid")
        .build();
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let ack = build_ack_node(&incoming.as_node_ref(), Some(&own_device_pn))
        .expect("message ack should be buildable");

    assert!(
        !ack.attrs.contains_key("recipient"),
        "ACK must NOT add `recipient` when the incoming stanza has none"
    );
}

#[test]
fn test_encode_ack_bytes_roundtrip_recipient() {
    // Exercises the real wire encoder (`encode_ack_bytes`), not just the
    // `build_ack_node` test mirror: serialize, decode the bytes back, and
    // assert the parsed ACK echoes `recipient` when present and omits it
    // when absent. Guards against the two builders silently diverging.
    let own_device_pn: Jid = "155500012345:48@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let with_recipient = NodeBuilder::new("message")
        .attr("from", "166361967902821@lid")
        .attr("id", "2A32F960553696093D99")
        .attr("type", "text")
        .attr("recipient", "146991363395800@lid")
        .build();
    let buf = encode_ack_bytes(
        &with_recipient.as_node_ref(),
        Some(&own_device_pn),
        AckParticipantPolicy::Preserve,
    )
    .expect("encode_ack_bytes should produce bytes");
    // The Encoder prepends a leading format byte (see `marshal`); the
    // decoder wants raw protocol bytes — same handling as `node_to_owned_ref`.
    let decoded =
        wacore_binary::marshal::unmarshal_ref(&buf[1..]).expect("encoded ack should decode");
    assert_eq!(decoded.tag, "ack");
    assert!(
        decoded
            .get_attr("class")
            .is_some_and(|v| v.as_str() == "message"),
        "decoded ack must have class=message"
    );
    assert!(
        decoded
            .get_attr("recipient")
            .is_some_and(|v| v.as_str() == "146991363395800@lid"),
        "encode_ack_bytes must echo `recipient` onto the wire"
    );
    assert!(
        decoded
            .get_attr("type")
            .is_some_and(|value| value.as_str() == "text"),
        "generic message ACK must echo its explicit type"
    );

    let without_recipient = NodeBuilder::new("message")
        .attr("from", "120363161500776365@g.us")
        .attr("id", "A5791A5392EF60E3FB06")
        .attr("type", "text")
        .attr("participant", "181531758878822@lid")
        .build();
    let buf = encode_ack_bytes(
        &without_recipient.as_node_ref(),
        Some(&own_device_pn),
        AckParticipantPolicy::Preserve,
    )
    .expect("encode_ack_bytes should produce bytes");
    let decoded =
        wacore_binary::marshal::unmarshal_ref(&buf[1..]).expect("encoded ack should decode");
    assert!(
        decoded.get_attr("recipient").is_none(),
        "encode_ack_bytes must not synthesise `recipient` when absent"
    );
}

#[test]
fn test_encode_ack_bytes_requires_public_response_inputs() {
    let without_id = NodeBuilder::new("receipt")
        .attr("from", "12025550111@s.whatsapp.net")
        .build();
    assert!(matches!(
        encode_ack_bytes(
            &without_id.as_node_ref(),
            None,
            AckParticipantPolicy::Preserve,
        ),
        Err(crate::features::StanzaResponseError::MissingAttribute("id"))
    ));

    let empty_id = NodeBuilder::new("receipt")
        .attr("id", "")
        .attr("from", "12025550111@s.whatsapp.net")
        .build();
    assert!(matches!(
        encode_ack_bytes(
            &empty_id.as_node_ref(),
            None,
            AckParticipantPolicy::Preserve,
        ),
        Err(crate::features::StanzaResponseError::MissingAttribute("id"))
    ));

    let without_from = NodeBuilder::new("receipt")
        .attr("id", "MISSING-FROM")
        .build();
    assert!(matches!(
        encode_ack_bytes(
            &without_from.as_node_ref(),
            None,
            AckParticipantPolicy::Preserve,
        ),
        Err(crate::features::StanzaResponseError::MissingAttribute(
            "from"
        ))
    ));

    let empty_from = NodeBuilder::new("receipt")
        .attr("id", "EMPTY-FROM")
        .attr("from", "")
        .build();
    assert!(matches!(
        encode_ack_bytes(
            &empty_from.as_node_ref(),
            None,
            AckParticipantPolicy::Preserve,
        ),
        Err(crate::features::StanzaResponseError::MissingAttribute(
            "from"
        ))
    ));

    let message = NodeBuilder::new("message")
        .attr("id", "MISSING-IDENTITY")
        .attr("from", "12025550111@s.whatsapp.net")
        .build();
    assert!(matches!(
        encode_ack_bytes(&message.as_node_ref(), None, AckParticipantPolicy::Preserve,),
        Err(crate::features::StanzaResponseError::MissingLocalIdentity)
    ));
}

#[test]
fn test_encode_ack_bytes_preserves_specialized_receipt_rules() {
    let from: Jid = "12025550111@s.whatsapp.net".parse().unwrap();
    let receipt = NodeBuilder::new("receipt")
        .attr("id", "RECEIPT-ACK")
        .attr("from", &from)
        .attr("participant", "12025550111@s.whatsapp.net")
        .attr("type", "retry")
        .build();
    let bytes = encode_ack_bytes(
        &receipt.as_node_ref(),
        None,
        AckParticipantPolicy::OmitReceiptDestinationDuplicate,
    )
    .expect("complete receipt should produce an ack");
    let ack = wacore_binary::marshal::unmarshal_ref(&bytes[1..])
        .expect("encoded receipt ack should decode");

    assert!(
        ack.get_attr("class")
            .is_some_and(|value| value.as_str() == "receipt")
    );
    assert!(
        ack.get_attr("type")
            .is_some_and(|value| value.as_str() == "retry")
    );
    assert!(
        ack.get_attr("participant").is_none(),
        "receipt ack must omit a participant that duplicates its destination"
    );
    assert!(ack.get_attr("from").is_none());

    let group_receipt = NodeBuilder::new("receipt")
        .attr("id", "GROUP-RECEIPT-ACK")
        .attr("from", "120363098765432100@g.us")
        .attr("participant", "12025550111:7@s.whatsapp.net")
        .build();
    let bytes = encode_ack_bytes(
        &group_receipt.as_node_ref(),
        None,
        AckParticipantPolicy::OmitReceiptDestinationDuplicate,
    )
    .expect("group receipt should produce an ack");
    let ack = wacore_binary::marshal::unmarshal_ref(&bytes[1..])
        .expect("encoded group receipt ack should decode");
    assert!(
        ack.get_attr("participant")
            .is_some_and(|value| value.as_str() == "12025550111:7@s.whatsapp.net"),
        "receipt ack must preserve a participant distinct from its destination"
    );

    let generic = NodeBuilder::new("message")
        .attr("id", "MESSAGE-ACK")
        .attr("from", "12025550111@s.whatsapp.net")
        .attr("participant", &from)
        .build();
    let bytes = encode_ack_bytes(
        &generic.as_node_ref(),
        Some(&from),
        AckParticipantPolicy::Preserve,
    )
    .expect("complete message should produce an ack");
    let ack = wacore_binary::marshal::unmarshal_ref(&bytes[1..])
        .expect("encoded message ack should decode");
    assert!(
        ack.get_attr("participant")
            .is_some_and(|value| value.as_str() == "12025550111@s.whatsapp.net"),
        "generic ack must not inherit the receipt-only participant rule"
    );
}

#[test]
fn test_encode_ack_bytes_compares_jid_participants_by_display() {
    let from = Jid {
        user: "12025550111".into(),
        server: wacore_binary::Server::Hosted,
        agent: 1,
        device: 7,
        integrator: 0,
    };
    let participant = Jid {
        agent: 2,
        ..from.clone()
    };
    assert_eq!(from.to_string(), participant.to_string());

    let receipt = NodeBuilder::new("receipt")
        .attr("id", "DISPLAY-EQUIVALENT-PARTICIPANT")
        .attr("from", &from)
        .attr("participant", &participant)
        .build();
    let bytes = encode_ack_bytes(
        &receipt.as_node_ref(),
        None,
        AckParticipantPolicy::OmitReceiptDestinationDuplicate,
    )
    .expect("complete receipt should produce an ack");
    let ack = wacore_binary::marshal::unmarshal_ref(&bytes[1..])
        .expect("encoded receipt ack should decode");

    assert!(
        ack.get_attr("participant").is_none(),
        "receipt ack must omit display-equivalent participant JIDs"
    );
}

#[test]
fn test_encode_ack_bytes_drops_encrypt_identity_notification_type() {
    let notification = NodeBuilder::new("notification")
        .attr("id", "IDENTITY-NOTIFICATION")
        .attr("from", "12025550111@s.whatsapp.net")
        .attr("type", "encrypt")
        .children([NodeBuilder::new("identity").build()])
        .build();
    let bytes = encode_ack_bytes(
        &notification.as_node_ref(),
        None,
        AckParticipantPolicy::Preserve,
    )
    .expect("complete notification should produce an ack");
    let ack = wacore_binary::marshal::unmarshal_ref(&bytes[1..])
        .expect("encoded notification ack should decode");

    assert!(
        ack.get_attr("class")
            .is_some_and(|value| value.as_str() == "notification")
    );
    assert!(ack.get_attr("type").is_none());
    assert!(ack.get_attr("from").is_none());
}

#[test]
fn test_encode_ack_bytes_preserves_call_class_and_type() {
    let call = NodeBuilder::new("call")
        .attr("id", "CALL-ACK")
        .attr("from", "12025550111@s.whatsapp.net")
        .attr("type", "offer_notice")
        .build();
    let bytes = encode_ack_bytes(&call.as_node_ref(), None, AckParticipantPolicy::Preserve)
        .expect("complete call should produce an ack");
    let ack =
        wacore_binary::marshal::unmarshal_ref(&bytes[1..]).expect("encoded call ack should decode");

    assert!(
        ack.get_attr("class")
            .is_some_and(|value| value.as_str() == "call")
    );
    assert!(
        ack.get_attr("type")
            .is_some_and(|value| value.as_str() == "offer_notice")
    );
    assert!(ack.get_attr("from").is_none());
}

/// Own-account fan-out ack must address back to the original `from` (own
/// LID) echoing `recipient`, not to the chat. Guards against regressing to
/// the chat-addressed `build_nack_node` style.
#[test]
fn test_message_ack_source_node_own_device_addressing() {
    use crate::types::message::{MessageInfo, MessageSource};
    // Own-account branch: sender == `from` (device-qualified), chat is the
    // device-stripped recipient. `to` must come from sender, not chat.
    let info = MessageInfo {
        id: "AC055553E56A2C12DE592DAD6353C477".to_string(),
        source: MessageSource {
            sender: "236395184570386@lid".parse().expect("sender"),
            chat: "156535032389744@lid".parse().expect("chat"),
            recipient: Some("156535032389744@lid".parse().expect("recipient")),
            is_group: false,
            ..Default::default()
        },
        ..Default::default()
    };
    let own_device_pn: Jid = "559984726662:95@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let source = message_ack_source_node(&info);
    let built = build_ack_node(&source.as_node_ref(), Some(&own_device_pn))
        .expect("message ack should be buildable");

    assert!(built.attrs.get("class").is_some_and(|v| v == "message"));
    assert!(
        built
            .attrs
            .get("to")
            .is_some_and(|v| v == "236395184570386@lid"),
        "ack `to` must be the original `from` (own LID), not the chat"
    );
    assert!(
        built
            .attrs
            .get("recipient")
            .is_some_and(|v| v == "156535032389744@lid"),
        "ack must echo `recipient` so the server can route/clear it"
    );
    assert!(
        !built.attrs.contains_key("type"),
        "message-class acks never carry a `type`"
    );
}

/// Common incoming DM from another user: `to` is the device-qualified
/// sender, with no `recipient`/`participant` synthesised.
#[test]
fn test_message_ack_source_node_incoming_dm_addressing() {
    use crate::types::message::{MessageInfo, MessageSource};
    let info = MessageInfo {
        id: "MSGID".to_string(),
        source: MessageSource {
            sender: "5511999998888:3@s.whatsapp.net".parse().expect("sender"),
            chat: "5511999998888@s.whatsapp.net".parse().expect("chat"),
            is_group: false,
            ..Default::default()
        },
        ..Default::default()
    };
    let own_device_pn: Jid = "559984726662:95@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let source = message_ack_source_node(&info);
    let built = build_ack_node(&source.as_node_ref(), Some(&own_device_pn))
        .expect("dm ack should be buildable");

    assert!(
        built
            .attrs
            .get("to")
            .is_some_and(|v| v == "5511999998888:3@s.whatsapp.net"),
        "ack `to` must be the device-qualified sender (the original `from`)"
    );
    assert!(!built.attrs.contains_key("recipient"));
    assert!(!built.attrs.contains_key("participant"));
}

/// status@broadcast (is_group=true in the parser) addresses the ack to the
/// status chat, with the sender as participant, not to the sender.
#[test]
fn test_message_ack_source_node_status_addressing() {
    use crate::types::message::{MessageInfo, MessageSource};
    let info = MessageInfo {
        id: "STATUSMSG".to_string(),
        source: MessageSource {
            chat: "status@broadcast".parse().expect("status chat"),
            sender: "181531758878822@lid".parse().expect("participant"),
            is_group: true,
            ..Default::default()
        },
        ..Default::default()
    };
    let own_device_pn: Jid = "559984726662:95@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let source = message_ack_source_node(&info);
    let built = build_ack_node(&source.as_node_ref(), Some(&own_device_pn))
        .expect("status ack should be buildable");

    assert!(
        built
            .attrs
            .get("to")
            .is_some_and(|v| v == "status@broadcast"),
        "status ack `to` must be the status chat, not the sender"
    );
    assert!(
        built
            .attrs
            .get("participant")
            .is_some_and(|v| v == "181531758878822@lid"),
        "status ack must preserve the sending participant"
    );
}

/// Group failure ack: `to` is the group, `participant` is preserved.
#[test]
fn test_message_ack_source_node_group_addressing() {
    use crate::types::message::{MessageInfo, MessageSource};
    // Group branch: chat == group `from`, sender == participant.
    let info = MessageInfo {
        id: "GROUPMSGID".to_string(),
        source: MessageSource {
            chat: "120363011111111111@g.us".parse().expect("group"),
            sender: "181531758878822@lid".parse().expect("participant"),
            is_group: true,
            ..Default::default()
        },
        ..Default::default()
    };
    let own_device_pn: Jid = "559984726662:95@s.whatsapp.net"
        .parse()
        .expect("own device PN JID should parse");

    let source = message_ack_source_node(&info);
    let built = build_ack_node(&source.as_node_ref(), Some(&own_device_pn))
        .expect("group message ack should be buildable");

    assert!(
        built
            .attrs
            .get("to")
            .is_some_and(|v| v == "120363011111111111@g.us"),
        "group ack `to` must be the group JID"
    );
    assert!(
        built
            .attrs
            .get("participant")
            .is_some_and(|v| v == "181531758878822@lid"),
        "group ack must preserve the sending `participant`"
    );
}

/// Smoke test: server ping with xmlns but no id attribute is handled.
#[tokio::test]
async fn test_handle_iq_ping_without_id() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Server ping without id — real format observed in production logs
    let ping_node = NodeBuilder::new("iq")
        .attr("type", "get")
        .attr("from", SERVER_JID)
        .attr("xmlns", "urn:xmpp:ping")
        .build();

    let handled = client.handle_iq(&ping_node.as_node_ref()).await;
    assert!(
        handled,
        "handle_iq must recognize ping without id attribute"
    );
}

// ── fibonacci_backoff tests ────────────────────────────────────────

#[test]
fn test_fibonacci_backoff_sequence() {
    // WA Web: first=1000, second=1000 → 1,1,2,3,5,8,13,21,34,55,89,144...s
    // We test base values without jitter by checking the range (±10%).
    let expected_base_ms = [1000, 1000, 2000, 3000, 5000, 8000, 13000, 21000];
    for (attempt, &base) in expected_base_ms.iter().enumerate() {
        let delay = fibonacci_backoff(attempt as u32);
        let ms = delay.as_millis() as u64;
        let low = base - base / 10;
        let high = base + base / 10;
        assert!(
            ms >= low && ms <= high,
            "attempt {attempt}: expected {low}..={high}ms, got {ms}ms"
        );
    }
}

#[test]
fn test_fibonacci_backoff_max_900s() {
    // After many attempts, should cap at 900s (±10%)
    let delay = fibonacci_backoff(100);
    let ms = delay.as_millis() as u64;
    assert!(
        ms <= 990_000,
        "should never exceed 900s + 10% jitter, got {ms}ms"
    );
    assert!(
        ms >= 810_000,
        "should be at least 900s - 10% jitter, got {ms}ms"
    );
}

#[test]
fn test_fibonacci_backoff_first_attempt_is_1s() {
    let delay = fibonacci_backoff(0);
    let ms = delay.as_millis() as u64;
    assert!(
        (900..=1100).contains(&ms),
        "first attempt should be ~1s (±10%), got {ms}ms"
    );
}

// ── connection stability / backoff reset (WA Web resetDelay) ────────

#[test]
fn should_reset_backoff_requires_uptime_window_and_no_penalty() {
    let start = 1_000_000i64;
    let stable = start + Client::STABLE_CONNECTION_RESET_MS;
    // Never authenticated this cycle → not stable, whatever the clock says.
    assert!(!should_reset_backoff(0, 1_000_000, false));
    // Authenticated but dropped inside the 30s window → keep escalating.
    assert!(!should_reset_backoff(
        start,
        start + Client::STABLE_CONNECTION_RESET_MS - 1,
        false
    ));
    // Survived the full window with no penalty → reset the backoff.
    assert!(should_reset_backoff(start, stable, false));
    assert!(should_reset_backoff(start, start + 60_000, false));
    // An explicit penalty (429 / manual reconnect) survives even a stable
    // connection (WA Web cancelReset).
    assert!(!should_reset_backoff(start, stable, true));
    assert!(!should_reset_backoff(start, start + 60_000, true));
    // A backwards clock jump must not underflow into a spurious reset.
    assert!(!should_reset_backoff(start, start - 5_000, false));
}

// ── stream error tests ─────────────────────────────────────────────

#[tokio::test]
async fn test_stream_error_401_disables_reconnect() {
    let client = create_offline_sync_test_client().await;
    let node = NodeBuilder::new("stream:error").attr("code", "401").build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        !client.enable_auto_reconnect.load(Ordering::Relaxed),
        "401 should disable auto-reconnect"
    );
}

#[tokio::test]
async fn test_stream_error_409_disables_reconnect() {
    let client = create_offline_sync_test_client().await;
    let node = NodeBuilder::new("stream:error").attr("code", "409").build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        !client.enable_auto_reconnect.load(Ordering::Relaxed),
        "409 should disable auto-reconnect"
    );
}

#[tokio::test]
async fn test_stream_error_429_keeps_reconnect_with_backoff() {
    let client = create_offline_sync_test_client().await;
    client.is_logged_in.store(true, Ordering::Relaxed);
    let before = client.auto_reconnect_errors.load(Ordering::Relaxed);
    let node = NodeBuilder::new("stream:error").attr("code", "429").build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        client.enable_auto_reconnect.load(Ordering::Relaxed),
        "429 should keep auto-reconnect enabled"
    );
    assert!(
        !client.is_logged_in.load(Ordering::Relaxed),
        "429 must clear is_logged_in so sends bail before the server flags abuse"
    );
    assert!(
        !client.expected_disconnect.load(Ordering::Relaxed),
        "429 must not mark the disconnect as expected (auto-reconnect path)"
    );
    let after = client.auto_reconnect_errors.load(Ordering::Relaxed);
    assert_eq!(
        after,
        before + 5,
        "429 should increase backoff by exactly 5: before={before}, after={after}"
    );
}

#[tokio::test]
async fn test_stream_error_503_keeps_reconnect() {
    let client = create_offline_sync_test_client().await;
    client.is_logged_in.store(true, Ordering::Relaxed);
    let node = NodeBuilder::new("stream:error").attr("code", "503").build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        client.enable_auto_reconnect.load(Ordering::Relaxed),
        "503 should keep auto-reconnect enabled"
    );
    assert!(
        !client.is_logged_in.load(Ordering::Relaxed),
        "503 must clear is_logged_in so sends bail against the dying socket"
    );
    assert!(
        !client.expected_disconnect.load(Ordering::Relaxed),
        "503 must not mark the disconnect as expected (auto-reconnect path)"
    );
}

#[tokio::test]
async fn test_stream_error_unknown_keeps_connection_alive() {
    // Unknown stream:error (no `code` attribute) must mirror whatsmeow's
    // default branch: log + dispatch event, but NOT mark this as an
    // expected disconnect. Setting that flag silently swallows the next
    // real disconnect and races the read loop into shutdown.
    let client = create_offline_sync_test_client().await;
    // Simulate an authenticated session before the stream error arrives.
    client.is_logged_in.store(true, Ordering::Relaxed);
    let node = NodeBuilder::new("stream:error").build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        client.is_logged_in.load(Ordering::Relaxed),
        "unknown stream:error must NOT log the client out"
    );
    assert!(
        !client.expected_disconnect.load(Ordering::Relaxed),
        "unknown stream:error must not mark the disconnect as expected"
    );
    assert!(
        client.enable_auto_reconnect.load(Ordering::Relaxed),
        "unknown stream:error must keep auto-reconnect enabled"
    );
}

#[tokio::test]
async fn test_stream_error_ack_shaped_does_not_force_shutdown() {
    // Server wraps per-stanza routing failures in `<stream:error><ack/>`
    // with no `code` attribute. Treat as informational, not as a fatal
    // stream teardown.
    let client = create_offline_sync_test_client().await;
    client.is_logged_in.store(true, Ordering::Relaxed);
    let ack_child = NodeBuilder::new("ack")
        .attr("class", "message")
        .attr("type", "text")
        .attr("id", "2A32F960553696093D99")
        .build();
    let node = NodeBuilder::new("stream:error")
        .children([ack_child])
        .build();
    client.handle_stream_error(&node.as_node_ref()).await;
    assert!(
        client.is_logged_in.load(Ordering::Relaxed),
        "ack-shaped stream:error must NOT log the client out"
    );
    assert!(
        !client.expected_disconnect.load(Ordering::Relaxed),
        "ack-shaped stream:error must not mark the disconnect as expected"
    );
}

#[tokio::test]
async fn test_custom_cache_config_is_respected() {
    use crate::cache_config::{CacheConfig, CacheEntryConfig};
    use std::time::Duration;

    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );

    let custom_config = CacheConfig {
        group_cache: CacheEntryConfig::new(Some(Duration::from_secs(60)), 10),
        device_registry_cache: CacheEntryConfig::new(Some(Duration::from_secs(60)), 10),
        ..CacheConfig::default()
    };

    // Verify that constructing a client with a custom config does not panic
    // and the client is usable.
    let (client, _rx) = Client::new_with_cache_config(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
        custom_config,
    )
    .await;

    assert!(!client.is_logged_in());
}

#[tokio::test]
async fn held_group_distribution_lane_survives_capacity_pressure() {
    let config = CacheConfig {
        group_distribution_locks_capacity: 1,
        ..Default::default()
    };
    let client = crate::test_utils::create_test_client_with_config(
        "group_distribution_eviction",
        Arc::new(MockHttpClient),
        config,
    )
    .await;

    let first: Jid = "120363000000000011@g.us".parse().unwrap();
    let second: Jid = "120363000000000012@g.us".parse().unwrap();
    let third: Jid = "120363000000000013@g.us".parse().unwrap();
    let held = client.group_distribution_lock(&first).await;

    drop(client.group_distribution_lock(&second).await);
    drop(client.group_distribution_lock(&third).await);

    let first_again = client
        .group_distribution_locks
        .get(&first)
        .await
        .expect("held lane must remain cached");
    assert!(
        first_again.try_lock().is_none(),
        "capacity pressure must not mint a second live lane"
    );
    let report = client.memory_report().await;
    assert_eq!(report.group_distribution_locks, 2);
    assert_eq!(report.group_distribution_lock_evictions, 1);
    assert_eq!(report.group_distribution_lock_eviction_blocks, 2);
    drop(held);
    assert!(first_again.try_lock().is_some());
}

#[tokio::test]
async fn active_chat_lane_survives_capacity_pressure() {
    fn test_lane() -> (ChatLane, async_channel::Receiver<QueuedChatMessage>) {
        let (queue_tx, queue_rx) = async_channel::unbounded();
        (
            ChatLane {
                enqueue_lock: Arc::new(Mutex::new(())),
                queue_tx,
            },
            queue_rx,
        )
    }

    let config = CacheConfig {
        chat_lanes_capacity: 1,
        ..Default::default()
    };
    let client = crate::test_utils::create_test_client_with_config(
        "chat_lane_eviction",
        Arc::new(MockHttpClient),
        config,
    )
    .await;

    let first: Jid = "120363000000000021@g.us".parse().unwrap();
    let second: Jid = "120363000000000022@g.us".parse().unwrap();
    let (first_lane, first_rx) = test_lane();
    let first_tx_probe = first_lane.queue_tx.clone();
    client.chat_lanes.insert(first.clone(), first_lane).await;

    let first_lane = client.chat_lanes.get(&first).await.unwrap();
    let node = NodeBuilder::new("message")
        .attr("from", first.clone())
        .attr("id", "ACTIVE-LANE-1")
        .build();
    first_lane.try_enqueue(node_to_owned_ref(node)).unwrap();
    drop(first_lane);
    let active_message = first_rx.recv().await.unwrap();

    let (second_lane, _second_rx) = test_lane();
    client.chat_lanes.insert(second, second_lane).await;

    let first_again = client
        .chat_lanes
        .get(&first)
        .await
        .expect("an active lane must remain cached");
    assert!(first_again.queue_tx.same_channel(&first_tx_probe));

    let next_node = NodeBuilder::new("message")
        .attr("from", first.clone())
        .attr("id", "ACTIVE-LANE-2")
        .build();
    first_again
        .try_enqueue(node_to_owned_ref(next_node))
        .unwrap();
    drop(first_again);
    drop(active_message);
    let next_active_message = first_rx.recv().await.unwrap();

    let third: Jid = "120363000000000023@g.us".parse().unwrap();
    let (third_lane, _third_rx) = test_lane();
    client.chat_lanes.insert(third, third_lane).await;
    assert!(
        client.chat_lanes.get(&first).await.is_some(),
        "a lane with an in-flight message must not be evicted"
    );

    drop(next_active_message);
    let fourth: Jid = "120363000000000024@g.us".parse().unwrap();
    let (fourth_lane, _fourth_rx) = test_lane();
    client.chat_lanes.insert(fourth, fourth_lane).await;
    assert!(
        client.chat_lanes.get(&first).await.is_none(),
        "an idle lane must become evictable again"
    );
}

/// Proves that `is_connected()` no longer gives false negatives under mutex
/// contention. Before the fix, `try_lock()` would fail when another task held
/// the noise_socket mutex, causing `is_connected()` to return `false` even
/// though the connection was alive — silently dropping receipt acks.
///
/// This test sets up a real NoiseSocket (same as socket unit tests) so it
/// accurately models the pre-fix scenario: socket is Some + mutex is held
/// by another task = old is_connected() returned false.
#[tokio::test]
async fn test_is_connected_not_affected_by_mutex_contention() {
    use crate::socket::NoiseSocket;
    use wacore::handshake::NoiseCipher;

    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Initially not connected
    assert!(!client.is_connected(), "should start disconnected");

    // Simulate a real connection: create a NoiseSocket and store it
    let transport: Arc<dyn crate::transport::Transport> =
        Arc::new(crate::transport::mock::MockTransport);
    let key = [0u8; 32];
    let write_key = NoiseCipher::new(&key).expect("valid key");
    let read_key = NoiseCipher::new(&key).expect("valid key");
    let noise_socket = NoiseSocket::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        transport,
        write_key,
        read_key,
    );
    *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
    client.is_connected.store(true, Ordering::Release);

    assert!(client.is_connected(), "should report connected");

    // Hold the noise_socket mutex — this used to make is_connected() return
    // false via try_lock() even though the socket was Some(...)
    let _guard = client.noise_socket.lock().await;
    assert!(
        client.is_connected(),
        "is_connected() must return true even while noise_socket mutex is held"
    );
}

#[tokio::test]
async fn disconnect_does_not_signal_connection_cleanup_before_outbound_flush() {
    use crate::socket::NoiseSocket;
    use async_trait::async_trait;
    use bytes::Bytes;
    use wacore::handshake::NoiseCipher;

    struct BlockingTransport {
        send_started: async_channel::Sender<()>,
        release_send: async_channel::Receiver<()>,
        send_done: Arc<AtomicBool>,
        disconnect_called: Arc<AtomicBool>,
        disconnect_before_send_done: Arc<AtomicBool>,
    }

    #[async_trait]
    impl crate::transport::Transport for BlockingTransport {
        async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
            let _ = self.send_started.try_send(());
            let _ = self.release_send.recv().await;
            self.send_done.store(true, Ordering::Release);
            Ok(())
        }

        async fn disconnect(&self) {
            if !self.send_done.load(Ordering::Acquire) {
                self.disconnect_before_send_done
                    .store(true, Ordering::Release);
            }
            self.disconnect_called.store(true, Ordering::Release);
        }
    }

    let client = crate::test_utils::create_test_client().await;
    let (send_started_tx, send_started_rx) = async_channel::bounded(1);
    let (release_send_tx, release_send_rx) = async_channel::bounded(1);
    let send_done = Arc::new(AtomicBool::new(false));
    let disconnect_called = Arc::new(AtomicBool::new(false));
    let disconnect_before_send_done = Arc::new(AtomicBool::new(false));

    let transport_impl = Arc::new(BlockingTransport {
        send_started: send_started_tx,
        release_send: release_send_rx,
        send_done: Arc::clone(&send_done),
        disconnect_called: Arc::clone(&disconnect_called),
        disconnect_before_send_done: Arc::clone(&disconnect_before_send_done),
    });
    let transport: Arc<dyn crate::transport::Transport> = transport_impl;

    let key = [0u8; 32];
    let write_key = NoiseCipher::new(&key).expect("valid key");
    let read_key = NoiseCipher::new(&key).expect("valid key");
    let noise_socket = NoiseSocket::new(
        client.runtime.clone(),
        Arc::clone(&transport),
        write_key,
        read_key,
    );

    *client.transport.lock().await = Some(transport);
    *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
    client.is_connected.store(true, Ordering::Release);

    let cleanup_signal = client.connection_shutdown_signal();
    let cleanup_client = Arc::clone(&client);
    let cleanup_task = tokio::spawn(async move {
        wacore::runtime::wait_for_shutdown(&cleanup_signal).await;
        cleanup_client.cleanup_connection_state().await;
    });

    let send_client = Arc::clone(&client);
    client.outbound_flush.spawn(&*client.runtime, async move {
        let receipt = NodeBuilder::new("receipt")
            .attr("id", "TEST-FLUSH-ORDER")
            .attr("to", "1234567890@s.whatsapp.net")
            .build();
        let _ = send_client.send_node(receipt).await;
    });

    tokio::time::timeout(Duration::from_secs(1), send_started_rx.recv())
        .await
        .expect("tracked send should start")
        .expect("send_started sender should stay open");

    let disconnect_client = Arc::clone(&client);
    let disconnect_task = tokio::spawn(async move {
        disconnect_client.disconnect().await;
    });

    // disconnect() closes the scope and then parks in `outbound_flush.flush`; the
    // parked flusher is what proves it got that far and is stuck there.
    crate::test_utils::poll_until("disconnect to park on the outbound flush", || {
        client.outbound_flush.flush_waiters() >= 1
    })
    .await;
    assert!(
        !client.connection_shutdown_signal().is_fired(),
        "connection cleanup must not fire while outbound flush is blocked"
    );
    assert!(
        !disconnect_called.load(Ordering::Acquire),
        "transport must stay open while outbound flush is blocked"
    );

    release_send_tx
        .send(())
        .await
        .expect("blocked send should still be waiting");

    tokio::time::timeout(Duration::from_secs(1), disconnect_task)
        .await
        .expect("disconnect should finish")
        .expect("disconnect task should not panic");
    tokio::time::timeout(Duration::from_secs(1), cleanup_task)
        .await
        .expect("cleanup should finish")
        .expect("cleanup task should not panic");

    assert!(send_done.load(Ordering::Acquire));
    assert!(disconnect_called.load(Ordering::Acquire));
    assert!(
        !disconnect_before_send_done.load(Ordering::Acquire),
        "cleanup closed the transport before the tracked send completed"
    );
}

async fn install_test_noise_socket(
    client: &Arc<Client>,
    transport: Arc<dyn crate::transport::Transport>,
    runtime: Arc<dyn Runtime>,
) {
    use crate::socket::NoiseSocket;
    use wacore::handshake::NoiseCipher;

    let key = [0u8; 32];
    let noise_socket = NoiseSocket::new(
        runtime,
        transport,
        NoiseCipher::new(&key).expect("valid key"),
        NoiseCipher::new(&key).expect("valid key"),
    );
    *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
    client.set_connected_for_test(true);
}

fn receipt_test_info(id: &str) -> Arc<crate::types::message::MessageInfo> {
    Arc::new(crate::types::message::MessageInfo {
        id: id.to_string(),
        source: crate::types::message::MessageSource {
            chat: "15550001111@s.whatsapp.net".parse().unwrap(),
            sender: "15550001111@s.whatsapp.net".parse().unwrap(),
            ..Default::default()
        },
        ..Default::default()
    })
}

#[derive(Debug)]
struct DropSpawnRuntime;

#[async_trait::async_trait]
impl Runtime for DropSpawnRuntime {
    fn spawn(
        &self,
        _future: std::pin::Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
    ) -> wacore::runtime::AbortHandle {
        // Dropping the sender future closes its receiver synchronously.
        wacore::runtime::AbortHandle::noop()
    }

    fn sleep(&self, _duration: Duration) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> {
        Box::pin(async {})
    }

    fn spawn_blocking(
        &self,
        operation: Box<dyn FnOnce() + Send + 'static>,
    ) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> {
        Box::pin(async move { operation() })
    }

    fn yield_now(&self) -> Option<std::pin::Pin<Box<dyn Future<Output = ()> + Send>>> {
        None
    }
}

#[tokio::test]
async fn raw_bytes_burst_drains_and_reuses_input_on_happy_paths() {
    use crate::transport::mock::CapturingMockTransport;

    let client = crate::test_utils::create_test_client().await;
    let transport = Arc::new(CapturingMockTransport::new());
    install_test_noise_socket(
        &client,
        transport.clone(),
        Arc::new(crate::runtime_impl::TokioRuntime),
    )
    .await;

    let mut frames = Vec::with_capacity(4);
    let retained_capacity = frames.capacity();
    frames.push(vec![0x11; 32]);
    // Sized for the largest burst below, so a reallocation here would mean the
    // callee replaced the buffer rather than filling it.
    let mut results = Vec::with_capacity(4);
    // Captured before the first call, not between the two: taken after it, a
    // replacement made on the single-frame path would already be the buffer
    // this compares against and would go unnoticed.
    let results_ptr = results.as_ptr();
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("installed socket");
    assert_eq!(results.len(), 1);
    assert!(results.iter().all(|result| result.is_ok()));
    assert_eq!(
        results.as_ptr(),
        results_ptr,
        "the single-frame path must fill the caller's buffer, not replace it"
    );
    assert!(frames.is_empty(), "the single-frame fast path must drain");
    assert_eq!(frames.capacity(), retained_capacity);

    frames.extend((0..4).map(|index| vec![index; 32]));
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("installed socket");
    assert_eq!(results.len(), 4);
    assert!(results.iter().all(|result| result.is_ok()));
    // Identity, not capacity: a fresh Vec of the same capacity would satisfy a
    // capacity check while defeating the whole point of the out-parameter. The
    // buffer is preallocated above so the second burst cannot legitimately
    // reallocate it.
    assert_eq!(
        results.as_ptr(),
        results_ptr,
        "the caller's results buffer must be the same allocation, not an equal one"
    );
    assert!(frames.is_empty(), "the joined path must drain");
    assert_eq!(frames.capacity(), retained_capacity);
    assert_eq!(transport.sent_count(), 5, "every frame must reach the wire");
    assert_eq!(
        transport.write_count(),
        2,
        "the four-frame call must remain one coalesced transport write"
    );
}

#[tokio::test]
async fn raw_bytes_burst_drains_input_when_disconnected() {
    let client = crate::test_utils::create_test_client().await;
    let mut frames = Vec::with_capacity(4);
    let retained_capacity = frames.capacity();
    frames.extend([vec![0x21; 32], vec![0x22; 32]]);

    let mut results = Vec::new();
    let result = client.send_raw_bytes_burst(&mut frames, &mut results).await;
    assert!(
        matches!(result, Err(ClientError::NotConnected)),
        "a missing socket must remain an outer NotConnected error: {result:?}"
    );
    assert!(frames.is_empty(), "the outer-error path must also drain");
    assert_eq!(frames.capacity(), retained_capacity);
}

#[tokio::test]
async fn raw_bytes_burst_surfaces_transport_then_poisoned_per_frame() {
    use crate::socket::error::EncryptSendErrorKind;
    use crate::transport::mock::CapturingMockTransport;

    let client = crate::test_utils::create_test_client().await;
    let transport = Arc::new(CapturingMockTransport::new());
    transport.fail_next_sends(1);
    install_test_noise_socket(
        &client,
        transport.clone(),
        Arc::new(crate::runtime_impl::TokioRuntime),
    )
    .await;

    let mut frames = Vec::with_capacity(4);
    let retained_capacity = frames.capacity();
    frames.push(vec![0x31; 32]);
    let mut results = Vec::new();
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("the socket lookup itself succeeds");
    let transport_error = results
        .pop()
        .expect("one result")
        .expect_err("the transport is configured to fail");
    assert!(matches!(
        transport_error.kind,
        EncryptSendErrorKind::Transport
    ));
    assert!(transport_error.is_transport_unavailable());
    assert!(frames.is_empty());
    assert_eq!(frames.capacity(), retained_capacity);

    frames.push(vec![0x32; 32]);
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("the installed socket remains reachable");
    let poisoned_error = results
        .pop()
        .expect("one result")
        .expect_err("the sender must reject work after an ambiguous write");
    assert!(matches!(
        poisoned_error.kind,
        EncryptSendErrorKind::Poisoned
    ));
    assert!(poisoned_error.is_transport_unavailable());
    assert!(frames.is_empty());
    assert_eq!(frames.capacity(), retained_capacity);
    assert_eq!(transport.failed_sends(), 1);
    assert_eq!(
        transport.write_count(),
        0,
        "a poisoned sender must not attempt another transport write"
    );
}

/// A burst hands every frame to the sender before awaiting any of them, which
/// is what lets them coalesce into one transport write. Awaiting each before
/// enqueueing the next would still deliver all four, in order, and produce four
/// writes instead of one -- so the write count is the assertion that separates
/// the two, and the ciphertext order is what pins the counter sequence the peer
/// will decrypt against.
#[tokio::test]
async fn a_multi_frame_burst_stays_one_ordered_write() {
    use crate::transport::mock::CapturingMockTransport;

    let client = crate::test_utils::create_test_client().await;
    let transport = Arc::new(CapturingMockTransport::new());
    install_test_noise_socket(
        &client,
        transport.clone(),
        Arc::new(crate::runtime_impl::TokioRuntime),
    )
    .await;

    // Distinct lengths, so a reordering is visible in the frame sizes even
    // though the payloads are encrypted on the way out.
    let mut frames: Vec<Vec<u8>> = (1..=4).map(|n| vec![n as u8; 16 * n]).collect();
    let mut results = Vec::new();
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("installed socket");

    assert_eq!(results.len(), 4);
    assert!(results.iter().all(|result| result.is_ok()));
    assert!(
        frames.is_empty(),
        "the burst must drain its input, which the workers rely on to refill it"
    );
    assert_eq!(
        transport.write_count(),
        1,
        "the whole burst must reach the transport as one write"
    );

    let sent = transport.sent();
    assert_eq!(sent.len(), 4, "every frame must reach the wire");
    // Each wire frame is its plaintext plus the AEAD tag and the length prefix,
    // a fixed function of the plaintext length, so the sizes identify which
    // plaintext landed where.
    const TAG_AND_PREFIX: usize = 16 + wacore::framing::FRAME_LENGTH_SIZE;
    let lengths: Vec<usize> = sent.iter().map(|frame| frame.len()).collect();
    assert_eq!(
        lengths,
        (1..=4)
            .map(|n| 16 * n + TAG_AND_PREFIX)
            .collect::<Vec<usize>>(),
        "frames must reach the wire in the order they were given"
    );
}

#[tokio::test]
async fn raw_bytes_burst_surfaces_a_closed_sender_per_frame() {
    use crate::socket::error::EncryptSendErrorKind;

    let client = crate::test_utils::create_test_client().await;
    install_test_noise_socket(
        &client,
        Arc::new(crate::transport::mock::MockTransport),
        Arc::new(DropSpawnRuntime),
    )
    .await;

    let mut frames = Vec::with_capacity(4);
    let retained_capacity = frames.capacity();
    frames.push(vec![0x41; 32]);
    let mut results = Vec::new();
    client
        .send_raw_bytes_burst(&mut frames, &mut results)
        .await
        .expect("the installed socket remains reachable");
    let error = results
        .pop()
        .expect("one result")
        .expect_err("the sender receiver was dropped at construction");
    assert!(matches!(error.kind, EncryptSendErrorKind::ChannelClosed));
    assert!(error.is_transport_unavailable());
    assert!(frames.is_empty());
    assert_eq!(frames.capacity(), retained_capacity);
}

/// Live delivery receipts flow through the persistent worker: the receipt
/// reaches the transport and the flush counter returns to zero afterwards.
#[tokio::test]
async fn delivery_receipt_worker_sends_and_releases_flush() {
    use crate::socket::NoiseSocket;
    use async_trait::async_trait;
    use bytes::Bytes;
    use wacore::handshake::NoiseCipher;

    struct CountingTransport {
        sends: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl crate::transport::Transport for CountingTransport {
        async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
            self.sends.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        async fn disconnect(&self) {}
    }

    let client = crate::test_utils::create_test_client().await;
    let sends = Arc::new(AtomicUsize::new(0));
    let transport: Arc<dyn crate::transport::Transport> = Arc::new(CountingTransport {
        sends: Arc::clone(&sends),
    });
    let key = [0u8; 32];
    let noise_socket = NoiseSocket::new(
        client.runtime.clone(),
        Arc::clone(&transport),
        NoiseCipher::new(&key).expect("valid key"),
        NoiseCipher::new(&key).expect("valid key"),
    );
    *client.transport.lock().await = Some(transport);
    *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
    client.is_connected.store(true, Ordering::Release);

    client.ack_received_message(&receipt_test_info("RCPT-WORKER-1"));

    let deadline = wacore::time::Instant::now() + Duration::from_secs(2);
    while sends.load(Ordering::SeqCst) == 0 {
        assert!(
            wacore::time::Instant::now() < deadline,
            "delivery receipt was never sent by the worker"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert_eq!(sends.load(Ordering::SeqCst), 1);

    client
        .outbound_flush
        .flush(&*client.runtime, Duration::from_secs(1))
        .await;
    assert_eq!(
        client.outbound_flush.pending(),
        0,
        "worker must release the flush guard after the send"
    );
}

/// Transport loss and the poisoned follow-up are reconnect signals, not
/// receipt-worker stalls: both must release their flush guards without a
/// second write attempt.
#[tokio::test]
async fn delivery_receipt_worker_releases_flush_after_transport_and_poisoned_failures() {
    use crate::transport::mock::CapturingMockTransport;

    let client = crate::test_utils::create_test_client().await;
    let transport = Arc::new(CapturingMockTransport::new());
    transport.fail_next_sends(1);
    install_test_noise_socket(
        &client,
        transport.clone(),
        Arc::new(crate::runtime_impl::TokioRuntime),
    )
    .await;

    client.ack_received_message(&receipt_test_info("RCPT-FAIL-1"));
    crate::test_utils::wait_for_outbound_tasks(&client).await;
    assert_eq!(client.outbound_flush.pending(), 0);
    assert_eq!(transport.failed_sends(), 1);

    client.ack_received_message(&receipt_test_info("RCPT-POISONED-2"));
    crate::test_utils::wait_for_outbound_tasks(&client).await;
    assert_eq!(client.outbound_flush.pending(), 0);
    assert_eq!(
        transport.failed_sends(),
        1,
        "the poisoned sender must reject locally instead of touching transport"
    );
    assert_eq!(transport.write_count(), 0);
}

/// A closed flush scope (disconnect in progress) drops live receipts without
/// leaking the flush counter — mirroring the previous spawn-per-receipt path.
#[tokio::test]
async fn delivery_receipt_dropped_when_flush_scope_closed() {
    let client = crate::test_utils::create_test_client().await;
    client.outbound_flush.close();

    client.ack_received_message(&receipt_test_info("RCPT-CLOSED-1"));

    assert_eq!(
        client.outbound_flush.pending(),
        0,
        "closed scope must not track new receipts"
    );
    // The drop happens before the queue: with the scope closed nothing may be
    // enqueued, so the lazy worker queue is never even created.
    assert!(
        client.delivery_receipt_queue.get().is_none(),
        "a dropped receipt must not reach the worker queue"
    );
    // Finishing well under the 5s flush timeout proves nothing was tracked;
    // the generous bound keeps this stable on oversubscribed CI runners.
    tokio::time::timeout(
        Duration::from_secs(2),
        client
            .outbound_flush
            .flush(&*client.runtime, Duration::from_secs(5)),
    )
    .await
    .expect("flush must not wait when nothing was queued");
}

/// Issue #571 under the worker model: `flush()` must wait for receipts that
/// are queued to the worker but not yet sent, including one queued behind an
/// in-flight blocked send.
#[tokio::test]
async fn flush_waits_for_queued_delivery_receipts() {
    use crate::socket::NoiseSocket;
    use async_trait::async_trait;
    use bytes::Bytes;
    use wacore::handshake::NoiseCipher;

    struct BlockingTransport {
        send_started: async_channel::Sender<()>,
        release_send: async_channel::Receiver<()>,
    }

    #[async_trait]
    impl crate::transport::Transport for BlockingTransport {
        async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
            let _ = self.send_started.try_send(());
            let _ = self.release_send.recv().await;
            Ok(())
        }
        async fn disconnect(&self) {}
    }

    let client = crate::test_utils::create_test_client().await;
    let (send_started_tx, send_started_rx) = async_channel::bounded(2);
    let (release_send_tx, release_send_rx) = async_channel::bounded(2);
    let transport: Arc<dyn crate::transport::Transport> = Arc::new(BlockingTransport {
        send_started: send_started_tx,
        release_send: release_send_rx,
    });
    let key = [0u8; 32];
    let noise_socket = NoiseSocket::new(
        client.runtime.clone(),
        Arc::clone(&transport),
        NoiseCipher::new(&key).expect("valid key"),
        NoiseCipher::new(&key).expect("valid key"),
    );
    *client.transport.lock().await = Some(transport);
    *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
    client.is_connected.store(true, Ordering::Release);

    client.ack_received_message(&receipt_test_info("RCPT-QUEUE-1"));
    tokio::time::timeout(Duration::from_secs(1), send_started_rx.recv())
        .await
        .expect("first receipt send should start")
        .expect("send_started sender should stay open");

    // Second receipt queues behind the blocked one and must also be tracked.
    client.ack_received_message(&receipt_test_info("RCPT-QUEUE-2"));
    assert_eq!(
        client.outbound_flush.pending(),
        2,
        "both the in-flight and the queued receipt must hold flush guards"
    );

    let flush_client = Arc::clone(&client);
    let flush_task = tokio::spawn(async move {
        flush_client
            .outbound_flush
            .flush(&*flush_client.runtime, Duration::from_secs(5))
            .await;
    });
    crate::test_utils::poll_until("the flusher to park on the outbound scope", || {
        client.outbound_flush.flush_waiters() >= 1
    })
    .await;
    assert!(
        !flush_task.is_finished(),
        "flush must wait while receipts are queued or in flight"
    );

    release_send_tx.send(()).await.expect("release first send");
    release_send_tx.send(()).await.expect("release second send");

    tokio::time::timeout(Duration::from_secs(2), flush_task)
        .await
        .expect("flush should finish once the queue drains")
        .expect("flush task should not panic");
    assert_eq!(client.outbound_flush.pending(), 0);
}

/// Verifies that `send_ack_for` returns an error (not silent Ok) when
/// disconnected. This ensures the caller's `warn!` fires so dropped acks
/// are visible in logs.
#[tokio::test]
async fn test_send_ack_for_returns_error_when_disconnected() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Not connected — send_ack_for should return Err, not Ok
    let receipt = NodeBuilder::new("receipt")
        .attr("from", "120363040237990503@g.us")
        .attr("id", "TEST-RECEIPT-ID")
        .attr("participant", "236395184570386@lid")
        .build();

    let result = client.send_ack_for(&receipt.as_node_ref()).await;
    assert!(
        matches!(result, Err(ClientError::NotConnected)),
        "send_ack_for must return Err(NotConnected) when disconnected, got: {result:?}"
    );
}

/// The gate that `send_ack_for` applies per ack, and that the burst path
/// applies once per burst, must agree on what counts as teardown. A burst that
/// missed it would write stale acks into a socket that is being torn down and
/// hold the outbound flush open until its timeout.
#[tokio::test]
async fn outbound_teardown_gate_covers_both_disconnect_signals() {
    let client = crate::test_utils::create_test_client().await;

    client.set_connected_for_test(true);
    client.expected_disconnect.store(false, Ordering::Relaxed);
    assert!(
        !client.outbound_teardown_in_progress(),
        "a live connection must not be treated as tearing down"
    );

    client.expected_disconnect.store(true, Ordering::Relaxed);
    assert!(
        client.outbound_teardown_in_progress(),
        "an expected disconnect (an intentional close, or a 515) must gate sends"
    );

    client.expected_disconnect.store(false, Ordering::Relaxed);
    client.set_connected_for_test(false);
    assert!(
        client.outbound_teardown_in_progress(),
        "a disconnected client must gate sends even without the expected flag"
    );
}

/// Exercise the actual deferred-ack worker, not only its predicate. Dropped
/// teardown batches must release guards, and reusing the batch buffer must not
/// leak either dropped ack into the next live burst.
#[tokio::test]
async fn deferred_ack_worker_drops_teardown_batches_and_recovers_cleanly() {
    use crate::transport::mock::CapturingMockTransport;

    let client = crate::test_utils::create_test_client().await;
    let transport = Arc::new(CapturingMockTransport::new());
    install_test_noise_socket(
        &client,
        transport.clone(),
        Arc::new(crate::runtime_impl::TokioRuntime),
    )
    .await;
    let receipt = |id| {
        let node = NodeBuilder::new("receipt")
            .attr("from", "15550001111@s.whatsapp.net")
            .attr("id", id)
            .build();
        crate::test_utils::node_to_owned_ref(&node)
    };

    client.expected_disconnect.store(true, Ordering::Relaxed);
    client
        .process_node(receipt("ACK-EXPECTED-DISCONNECT"))
        .await;
    crate::test_utils::wait_for_outbound_tasks(&client).await;
    assert_eq!(transport.sent_count(), 0);

    client.expected_disconnect.store(false, Ordering::Relaxed);
    client.set_connected_for_test(false);
    client.process_node(receipt("ACK-DISCONNECTED")).await;
    crate::test_utils::wait_for_outbound_tasks(&client).await;
    assert_eq!(transport.sent_count(), 0);

    client.set_connected_for_test(true);
    client.process_node(receipt("ACK-LIVE")).await;
    crate::test_utils::wait_for_outbound_tasks(&client).await;
    assert_eq!(
        transport.sent_count(),
        1,
        "only the live ack may survive into the reusable batch"
    );
    assert_eq!(client.outbound_flush.pending(), 0);
}

/// Verifies that `send_ack_for` returns Ok when expected_disconnect is set,
/// since this is an intentional shutdown path.
#[tokio::test]
async fn test_send_ack_for_returns_ok_on_expected_disconnect() {
    let backend = crate::test_utils::create_test_backend().await;
    let pm = Arc::new(
        PersistenceManager::new(backend)
            .await
            .expect("persistence manager should initialize"),
    );
    let (client, _rx) = Client::new(
        Arc::new(crate::runtime_impl::TokioRuntime),
        pm,
        Arc::new(crate::transport::mock::MockTransportFactory::new()),
        Arc::new(MockHttpClient),
        None,
    )
    .await;

    // Set expected disconnect — send_ack_for should gracefully return Ok
    client.expected_disconnect.store(true, Ordering::Relaxed);

    let receipt = NodeBuilder::new("receipt")
        .attr("from", "120363040237990503@g.us")
        .attr("id", "TEST-RECEIPT-ID")
        .build();

    let result = client.send_ack_for(&receipt.as_node_ref()).await;
    assert!(
        result.is_ok(),
        "send_ack_for should return Ok during expected disconnect"
    );
}

// Per-connection notify must NOT set the terminal sticky flag; if it did,
// every reconnect would instantly abort subscribers registered on the
// terminal signal. Regression guard for the CI breakage observed on PR #560.
#[tokio::test]
async fn per_connection_notify_leaves_terminal_signal_untouched() {
    let client = crate::test_utils::create_test_client().await;

    client.notify_connection_shutdown();

    assert!(
        !client.shutdown_signal().is_fired(),
        "terminal shutdown must stay clean when only per-connection fires"
    );
}

// Subscribers registered AFTER a reset must not see the previous
// notifier's fired state. This is the core property that makes reconnect
// work: after cleanup_connection_state notifies the per-connection
// signal, the next connection replaces it with a fresh one.
#[tokio::test]
async fn reset_gives_fresh_per_connection_notifier() {
    let client = crate::test_utils::create_test_client().await;

    client.notify_connection_shutdown();
    assert!(
        client.connection_shutdown_signal().is_fired(),
        "subscriber BEFORE reset sees the notify on the current notifier"
    );

    client.reset_connection_shutdown();

    assert!(
        !client.connection_shutdown_signal().is_fired(),
        "subscribers AFTER reset must NOT see the previous notifier's state"
    );
}

// Capture-once regression guard: a ShutdownSignal captured before a reset
// must keep observing the pre-reset fired state. Without this, a
// reconnect after the old notifier is replaced in the Mutex would
// strand long-lived tasks (e.g. keepalive) on a new notifier they
// never registered for. See keepalive_loop which captures its signal
// once at task startup.
#[tokio::test]
async fn captured_signal_keeps_observing_old_notifier_after_reset() {
    let client = crate::test_utils::create_test_client().await;

    let captured = client.connection_shutdown_signal();
    client.notify_connection_shutdown();
    client.reset_connection_shutdown();

    assert!(
        captured.is_fired(),
        "captured signal must retain the pre-reset notifier's fired state"
    );
}

// Terminal disconnect() must also wake per-connection subscribers via
// cleanup_connection_state, so keepalive/request/read loop exit promptly.
#[tokio::test]
async fn terminal_disconnect_propagates_to_per_connection_signal() {
    let client = crate::test_utils::create_test_client().await;
    let conn_signal = client.connection_shutdown_signal();

    client.disconnect().await;

    assert!(
        conn_signal.is_fired(),
        "disconnect must fire per-connection via cleanup_connection_state"
    );
    assert!(
        client.shutdown_signal().is_fired(),
        "disconnect must also fire terminal"
    );
}

/// Dropping the last owner must release persistence handles promptly.
#[tokio::test]
async fn dropping_fresh_client_releases_it_without_shutdown() {
    let client = crate::test_utils::create_test_client().await;
    let weak = Arc::downgrade(&client);

    drop(client);

    tokio::time::timeout(Duration::from_secs(5), async {
        while weak.strong_count() != 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap_or_else(|_| {
        panic!(
            "client is still retained by a background task (strong_count={})",
            weak.strong_count()
        )
    });
}

/// Locks the zero-allocation property of the ack miss path: id resolution and
/// the waiter probe must borrow from the node buffer. An `into_owned()` here
/// costs one String per received ack, which the e2e dhat profile caught live.
#[tokio::test]
async fn ack_miss_path_does_not_heap_allocate() {
    let client = crate::test_utils::create_test_client().await;

    let node = Arc::new(owned_ack_node("3EB0A9252A8F12B7E2"));

    // A per-call String shows up in every window, so the minimum only reaches 0
    // when the path is clean.
    let min_delta = crate::test_alloc::min_allocs(0, || {
        let handled = client.handle_ack_response_arc(&node);
        assert!(!handled, "no waiter is registered for this id");
    });
    assert_eq!(min_delta, 0, "ack miss path must not allocate");
}

/// The public stats snapshot must reflect the client's counters plus the
/// client-level fields (reconnect errors, throttled resends) it fills in.
#[tokio::test]
async fn stats_snapshot_reflects_counters() {
    let client = crate::test_utils::create_test_client().await;

    client.stats.record_frame_sent(150);
    client.stats.record_recv_batch(300, 2);
    client.stats.record_message_sent();
    client.auto_reconnect_errors.store(3, Ordering::Relaxed);

    let snap = client.stats();
    assert_eq!(snap.bytes_sent, 150);
    assert_eq!(snap.frames_sent, 1);
    assert_eq!(snap.bytes_received, 300);
    assert_eq!(snap.frames_received, 2);
    assert_eq!(snap.messages_sent, 1);
    assert_eq!(snap.reconnect_errors, 3);
    assert_eq!(snap.resends_throttled, 0);
}

/// A clock read leaves the module on wasm32/embedded, so the wire path owes a
/// budget: only the send that arms the dead-socket anchor may date itself, and
/// only one stamp may be spent per received transport event.
#[test]
fn wire_bookkeeping_reads_the_clock_only_where_a_value_is_used() {
    use wacore::time::clock_reads;

    let stats = wacore::stats::SessionStats::new();

    let arming = clock_reads::snapshot();
    stats.record_frame_sent(10);
    assert_eq!(
        clock_reads::since(arming).wall,
        1,
        "the send that arms the anchor dates it"
    );

    let armed = clock_reads::snapshot();
    for _ in 0..16 {
        stats.record_frame_sent(10);
    }
    assert_eq!(
        clock_reads::since(armed).wall,
        0,
        "sends under an already-armed anchor have nothing to date"
    );

    let recv = clock_reads::snapshot();
    stats.mark_recv_activity();
    stats.record_recv_batch(100, 1);
    assert_eq!(
        clock_reads::since(recv).wall,
        1,
        "a single-frame batch is stamped once, at arrival"
    );

    let long_batch = clock_reads::snapshot();
    stats.mark_recv_activity();
    stats.record_recv_batch(100, 4);
    assert_eq!(
        clock_reads::since(long_batch).wall,
        2,
        "a long batch re-stamps on completion so a slow drain is not read as silence"
    );

    let rearm = clock_reads::snapshot();
    stats.record_frame_sent(10);
    assert_eq!(
        clock_reads::since(rearm).wall,
        1,
        "the receive cancelled the anchor, so this send arms it again"
    );
}

/// Handling a received stanza must not ask for the time: the read loop already
/// stamped arrival, and nothing downstream of it dates anything.
#[tokio::test]
async fn received_stanza_handling_reads_no_clock() {
    use wacore::time::clock_reads;

    let client = crate::test_utils::create_test_client().await;
    let receipt = || {
        to_owned_node(
            &NodeBuilder::new("receipt")
                .attr("id", "3EB0AABBCCDDEEFF001122")
                .attr("from", "5511900000001@s.whatsapp.net")
                .attr("t", "1780000000")
                .build(),
        )
    };

    client.process_decrypted_node(receipt()).await;
    crate::test_utils::wait_for_outbound_tasks(&client).await;

    let base = clock_reads::snapshot();
    client.process_decrypted_node(receipt()).await;
    let reads = clock_reads::since(base);

    assert_eq!(reads.wall, 0, "receipt handling reads no wall clock");
    assert_eq!(
        reads.monotonic, 0,
        "receipt handling reads no monotonic clock"
    );
}

/// memory_report must be callable on a fresh client and internally
/// consistent: empty collections report zero entries and zero bytes.
/// The Display sections are sliced by hard-coded boundaries over
/// `collections()`, so adding a cache without moving the boundary silently
/// prints it under the wrong heading and drops the last one of the next
/// section. This pins the layout instead of the individual counts.
#[tokio::test]
async fn memory_report_display_sections_stay_aligned() {
    let client = crate::test_utils::create_test_client_with_name("memory_report_sections").await;
    let rendered = client.memory_report().await.to_string();

    let ttl_start = rendered
        .find("--- TTL-bounded caches ---")
        .expect("ttl section");
    let signal_start = rendered.find("--- Signal store").expect("signal section");
    let ttl_block = &rendered[ttl_start..signal_start];

    for name in [
        "group_cache:",
        "device_registry_cache:",
        "recent_messages:",
        "group_devices_memo:",
        "dm_devices_memo:",
    ] {
        assert!(
            ttl_block.contains(name),
            "{name} must render under the TTL-bounded heading, got:\n{rendered}"
        );
    }
    for name in [
        "signal_sessions:",
        "signal_identities:",
        "signal_sender_keys:",
    ] {
        assert!(
            rendered[signal_start..].contains(name),
            "{name} must render under the Signal heading, got:\n{rendered}"
        );
    }
}

#[tokio::test]
async fn memory_report_on_fresh_client() {
    // recent_messages is capacity-0 (disabled) by default; enable it so the
    // byte-attribution assertion below has a collection to land in.
    let mut cache_config = CacheConfig::default();
    cache_config.recent_messages =
        crate::cache_config::CacheEntryConfig::new(Some(Duration::from_secs(300)), 64);
    let client = crate::test_utils::create_test_client_with_config(
        "memory_report",
        Arc::new(MockHttpClient),
        cache_config,
    )
    .await;

    let report = client.memory_report().await;
    assert_eq!(report.recent_messages.entries, 0);
    assert_eq!(report.recent_messages.bytes, 0);
    assert_eq!(report.group_distribution_locks, 0);
    assert_eq!(report.group_distribution_lock_evictions, 0);
    assert_eq!(report.group_distribution_lock_eviction_blocks, 0);
    assert_eq!(report.signal_sessions.entries, 0);
    assert_eq!(report.response_waiters, 0);

    // Retained bytes must appear once something is cached.
    let key = ChatMessageId::new(
        "559980000001@s.whatsapp.net".parse().unwrap(),
        "3EB0TESTMSGID".to_string(),
    );
    client
        .recent_messages
        .insert(key, Arc::new(vec![0u8; 2048]))
        .await;
    let report = client.memory_report().await;
    assert_eq!(report.recent_messages.entries, 1);
    assert!(
        report.recent_messages.bytes >= 2048,
        "cached payload bytes must be attributed (got {})",
        report.recent_messages.bytes
    );
    assert!(report.total_estimated_bytes() >= 2048);
    // Display must render without panicking.
    let _ = report.to_string();
}

/// resource_report (workstream F) composes the client's own memory_report with
/// the out-of-client components, folds in an AllocMeter snapshot when installed,
/// and is Display-able.
#[tokio::test]
async fn resource_report_composes_client_and_out_of_client_components() {
    use wacore::stats::{AllocMeter, TaskInstrument};

    let client = crate::test_utils::create_test_client().await;

    let report = client.resource_report().await;

    // The client sub-report equals memory_report's total.
    let mem = client.memory_report().await;
    assert_eq!(
        report.client.total_estimated_bytes(),
        mem.total_estimated_bytes()
    );

    // The SQLite backend is intentionally best-effort and uses a non-blocking pool checkout.
    // A concurrently held single connection may therefore report no storage sample; when a sample
    // is available, its two SQLite-derived fields must remain coherent. The backend's dedicated
    // resource-report test deterministically verifies the concrete page-cache calculation.
    assert_eq!(
        report.storage.memory_bytes.is_some(),
        report.storage.pages.is_some()
    );

    // No transport is connected and the mock HTTP client reports nothing.
    assert!(report.transport.is_none());
    assert!(report.http.is_none());
    assert!(report.alloc.is_none(), "no alloc meter installed yet");

    // The total includes the storage estimate on top of client collections.
    assert!(report.total_estimated_bytes() >= report.storage.total_bytes());
    let _ = report.to_string();

    // Install an alloc meter and charge a known allocation inside a poll scope;
    // the next report folds in its snapshot.
    let meter = Arc::new(AllocMeter::new());
    meter.on_poll_start();
    AllocMeter::on_alloc(4096);
    meter.on_poll_end();
    let _ = client.alloc_meter.set(meter);

    let report = client.resource_report().await;
    let alloc = report
        .alloc
        .expect("alloc snapshot folded in once installed");
    assert_eq!(alloc.allocated_bytes, 4096);
    assert_eq!(alloc.allocations, 1);
}

/// InstrumentedRuntime must invoke the TaskInstrument around polls of spawned
/// futures and blocking closures, and CpuMeter must accumulate them.
#[tokio::test]
async fn instrumented_runtime_reports_to_cpu_meter() {
    use wacore::runtime::Runtime as _;
    use wacore::stats::{CpuMeter, InstrumentedRuntime};

    let meter = Arc::new(CpuMeter::new());
    let runtime =
        InstrumentedRuntime::new(Arc::new(crate::runtime_impl::TokioRuntime), meter.clone());

    let (tx, rx) = oneshot::channel::<()>();
    runtime
        .spawn(Box::pin(async move {
            let _ = tx.send(());
        }))
        .detach();
    rx.await.expect("spawned future ran");

    let after_spawn = meter.snapshot();
    assert!(after_spawn.polls >= 1, "spawned future polls are metered");

    runtime.spawn_blocking(Box::new(|| {})).await;
    let after_blocking = meter.snapshot();
    assert!(
        after_blocking.polls > after_spawn.polls,
        "blocking work is metered too"
    );
}

/// A status@broadcast stanza feeds the same per-chat queue a `<message>` does,
/// so its enqueue must keep the read loop's arrival order.
#[tokio::test]
async fn status_broadcast_stanzas_are_dispatched_inline() {
    use wacore_binary::builder::NodeBuilder;

    let client = create_offline_sync_test_client().await;

    let status = NodeBuilder::new("status")
        .attr("from", "status@broadcast")
        .attr("id", "INLINE-1")
        .build();
    assert!(
        client.processes_inline(&status.as_node_ref()),
        "a status@broadcast stanza must keep the read loop's arrival order"
    );

    let message = NodeBuilder::new("message")
        .attr("from", "status@broadcast")
        .attr("id", "INLINE-2")
        .build();
    assert!(
        client.processes_inline(&message.as_node_ref()),
        "the pre-existing <message> form is unchanged"
    );

    let newsletter_status = NodeBuilder::new("status")
        .attr("from", "120363298765432100@newsletter")
        .attr("id", "INLINE-3")
        .build();
    assert!(
        !client.processes_inline(&newsletter_status.as_node_ref()),
        "a newsletter <status> has no per-chat queue to order"
    );
}

/// The server counts status updates and calls separately, so a preview that
/// only reports messages/notifications/receipts leaves part of the backlog
/// unaccounted for.
#[tokio::test]
async fn offline_preview_reports_status_and_call_counts() {
    use wacore::types::events::{Event, EventHandler};

    #[derive(Default)]
    struct PreviewRecorder {
        previews: std::sync::Mutex<Vec<wacore::types::events::OfflineSyncPreview>>,
    }

    impl EventHandler for PreviewRecorder {
        fn handle_event(&self, event: Arc<Event>) {
            if let Event::OfflineSyncPreview(preview) = &*event {
                self.previews.lock().unwrap().push(preview.clone());
            }
        }
    }

    let client = create_offline_sync_test_client().await;
    let recorder = Arc::new(PreviewRecorder::default());
    client
        .core
        .event_bus
        .subscribe_handler(recorder.clone())
        .detach();

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("offline_preview")
            .attr("count", "9")
            .attr("message", "2")
            .attr("notification", "1")
            .attr("receipt", "1")
            .attr("appdata", "1")
            .attr("call", "1")
            .attr("status", "3")
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;

    let previews = recorder.previews.lock().unwrap();
    let preview = previews
        .first()
        .expect("a preview event must be dispatched");
    assert_eq!(preview.total, 9);
    assert_eq!(preview.messages, 2);
    assert_eq!(preview.notifications, 1);
    assert_eq!(preview.receipts, 1);
    assert_eq!(preview.app_data_changes, 1);
    assert_eq!(preview.calls, 1);
    assert_eq!(preview.statuses, 3);
}

/// A preview from a server that never sends the newer counts still parses.
#[tokio::test]
async fn offline_preview_defaults_absent_counts_to_zero() {
    use wacore::types::events::{Event, EventHandler};

    #[derive(Default)]
    struct PreviewRecorder {
        previews: std::sync::Mutex<Vec<wacore::types::events::OfflineSyncPreview>>,
    }

    impl EventHandler for PreviewRecorder {
        fn handle_event(&self, event: Arc<Event>) {
            if let Event::OfflineSyncPreview(preview) = &*event {
                self.previews.lock().unwrap().push(preview.clone());
            }
        }
    }

    let client = create_offline_sync_test_client().await;
    let recorder = Arc::new(PreviewRecorder::default());
    client
        .core
        .event_bus
        .subscribe_handler(recorder.clone())
        .detach();

    let node = NodeBuilder::new("ib")
        .children([NodeBuilder::new("offline_preview")
            .attr("count", "1")
            .attr("message", "1")
            .build()])
        .build();

    client.process_node(node_to_owned_ref(node)).await;

    let previews = recorder.previews.lock().unwrap();
    let preview = previews
        .first()
        .expect("a preview event must be dispatched");
    assert_eq!(preview.total, 1);
    assert_eq!(preview.calls, 0);
    assert_eq!(preview.statuses, 0);
}

/// A phash waiter is resolved by an ack that may never arrive, and nothing
/// polls it. The sweep has to drop the stale one, or a non-empty map reads as
/// "IQ pending" and silences pings for the life of the connection.
#[test]
fn phash_waiter_sweep_drops_only_entries_that_lived_through_a_sweep() {
    use crate::client::{PhashWaiter, ResponseWaiter, ResponseWaiterMap};
    use futures::channel::oneshot;

    let mut map = ResponseWaiterMap::default();
    let waiter = |registered_epoch: u64| {
        ResponseWaiter::Phash(PhashWaiter {
            expected: wacore_binary::CompactString::from("hash"),
            jid: "13135550100@s.whatsapp.net".parse().expect("valid jid"),
            invalidate_group_cache: false,
            registered_epoch,
        })
    };

    let epoch = map.current_epoch();
    map.insert("first".to_string(), waiter(epoch));
    let (iq_tx, _iq_rx) = oneshot::channel();
    map.insert("iq".to_string(), ResponseWaiter::Iq(iq_tx));

    // One sweep is not enough: the waiter registered in the current epoch is
    // still within its window, so an ack in flight is not discarded early.
    map.drop_expired_phash();
    assert!(
        map.remove("first").is_some(),
        "a waiter must survive the sweep of the epoch it registered in"
    );

    // Registered before a sweep, then swept again: now it is stale.
    let epoch = map.current_epoch();
    map.insert("stale".to_string(), waiter(epoch));
    map.drop_expired_phash();
    map.drop_expired_phash();
    assert!(
        map.remove("stale").is_none(),
        "a waiter that lived through a full sweep must be dropped"
    );
    assert!(
        map.remove("iq").is_some(),
        "the sweep must never touch IQ waiters, which have their own cleanup"
    );
}

/// A non-reconnectable connect failure releases work parked in
/// `await_connection`, having decided the session is over.
///
/// What this pins is the outcome, and only that. It does **not** pin the order
/// of the stores and the notify inside `handle_connect_failure`, and no test at
/// this level can: nothing awaits between them, so the waiter is never
/// scheduled into the gap and the assertions below hold either way. Reordering
/// them keeps this test green.
///
/// That order is held by the comment at the notify, not from here. It is worth
/// holding because the announcement is what wakes the wait, and the wait
/// answers by reading state — announcing first offers it a client that has not
/// yet decided. Pinning it would mean a pause hook between the two, in
/// production code, to catch a race that `cleanup_connection_state` and the run
/// loop's exit both go on to correct. Not worth the hook.
#[tokio::test]
async fn a_terminal_connect_failure_releases_a_parked_wait() {
    let client = create_offline_sync_test_client().await;
    client.is_running.store(true, Ordering::Relaxed);

    let waiter = {
        let client = Arc::clone(&client);
        tokio::spawn(async move { client.await_connection().await })
    };
    crate::test_utils::poll_until("the waiter to park on the notifier", || {
        client.session_state_notifier.total_listeners() >= 1
    })
    .await;

    // 403 is REASON_LOCKED: not transient, so no replacement is coming.
    let failure = NodeBuilder::new("failure").attr("reason", "403").build();
    client.handle_connect_failure(&failure.as_node_ref()).await;

    assert!(
        client.is_terminal(),
        "the failure decided the session is over"
    );
    assert!(
        !tokio::time::timeout(Duration::from_secs(5), waiter)
            .await
            .expect("and the wait must end on that decision")
            .expect("the waiter should not panic"),
        "reporting that no connection arrived"
    );
}