whatsapp-rust 0.5.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
use crate::client::Client;
use crate::store::signal_adapter::SignalProtocolStoreAdapter;
use crate::types::events::Event;
use crate::types::message::MessageInfo;
use log::{debug, warn};
use prost::Message as ProtoMessage;

use std::sync::Arc;
use wacore::libsignal::crypto::DecryptionError;
use wacore::libsignal::protocol::SenderKeyDistributionMessage;
use wacore::libsignal::protocol::group_decrypt;
use wacore::libsignal::protocol::process_sender_key_distribution_message;
use wacore::libsignal::protocol::{
    PreKeySignalMessage, SignalMessage, SignalProtocolError, UsePQRatchet, message_decrypt,
};
use wacore::libsignal::protocol::{
    PublicKey as SignalPublicKey, SENDERKEY_MESSAGE_CURRENT_VERSION,
};
use wacore::libsignal::store::sender_key_name::SenderKeyName;
use wacore::types::jid::JidExt;
use wacore_binary::jid::Jid;
use wacore_binary::jid::JidExt as _;
use wacore_binary::node::Node;
use waproto::whatsapp::{self as wa};

/// Maximum retry attempts per message (matches WhatsApp Web's MAX_RETRY = 5).
/// After this many retries, we stop sending retry receipts and rely solely on PDO.
const MAX_DECRYPT_RETRIES: u8 = 5;

/// Retry count threshold for logging high retry warnings.
/// WhatsApp Web logs metrics when retry count exceeds this value.
const HIGH_RETRY_COUNT_THRESHOLD: u8 = 3;

pub(crate) use wacore::protocol::retry::RetryReason;

impl Client {
    /// Dispatches a successfully parsed message to the event bus and sends a delivery receipt.
    fn dispatch_parsed_message(self: &Arc<Self>, msg: wa::Message, info: &MessageInfo) {
        // Send delivery receipt immediately in the background.
        let client_clone = self.clone();
        let info_clone = info.clone();
        self.runtime
            .spawn(Box::pin(async move {
                client_clone.send_delivery_receipt(&info_clone).await;
            }))
            .detach();

        // Dispatch to event bus
        self.core
            .event_bus
            .dispatch(&Event::Message(Box::new(msg), info.clone()));
    }

    /// Handles a newsletter plaintext message.
    /// Newsletters are not E2E encrypted and use the <plaintext> tag directly.
    async fn handle_newsletter_message(self: &Arc<Self>, node: &Node, info: &MessageInfo) {
        let Some(plaintext_node) = node.get_optional_child_by_tag(&["plaintext"]) else {
            log::warn!(
                "[msg:{}] Received newsletter message without <plaintext> child: {}",
                info.id,
                node.tag
            );
            return;
        };

        if let Some(wacore_binary::node::NodeContent::Bytes(bytes)) = &plaintext_node.content {
            match wa::Message::decode(bytes.as_slice()) {
                Ok(msg) => {
                    log::info!(
                        "[msg:{}] Received newsletter plaintext message from {}",
                        info.id,
                        info.source.chat
                    );
                    self.dispatch_parsed_message(msg, info);
                }
                Err(e) => {
                    log::warn!(
                        "[msg:{}] Failed to decode newsletter plaintext: {e}",
                        info.id
                    );
                }
            }
        }
    }
    /// Dispatches an `UndecryptableMessage` event to notify consumers that a message
    /// could not be decrypted. This is called when decryption fails and we need to
    /// show a placeholder to the user (like "Waiting for this message...").
    ///
    /// # Arguments
    /// * `info` - The message info for the undecryptable message
    /// * `decrypt_fail_mode` - Whether to show or hide the placeholder (matches WhatsApp Web's `hideFail`)
    fn dispatch_undecryptable_event(
        &self,
        info: &MessageInfo,
        decrypt_fail_mode: crate::types::events::DecryptFailMode,
    ) {
        self.core.event_bus.dispatch(&Event::UndecryptableMessage(
            crate::types::events::UndecryptableMessage {
                info: info.clone(),
                is_unavailable: false,
                unavailable_type: crate::types::events::UnavailableType::Unknown,
                decrypt_fail_mode,
            },
        ));
    }

    /// Handles a decryption failure by dispatching an undecryptable event and spawning a retry receipt.
    ///
    /// This is a convenience method that combines the common pattern of:
    /// 1. Dispatching an UndecryptableMessage event
    /// 2. Spawning a retry receipt to request re-encryption
    ///
    /// Returns `true` to be assigned to `dispatched_undecryptable` flag.
    fn handle_decrypt_failure(
        self: &Arc<Self>,
        info: &MessageInfo,
        reason: RetryReason,
        decrypt_fail_mode: crate::types::events::DecryptFailMode,
    ) -> bool {
        self.dispatch_undecryptable_event(info, decrypt_fail_mode);
        self.spawn_retry_receipt(info, reason);
        true
    }

    /// Increments the retry count for a message and returns the new count.
    /// Returns `None` if max retries have been reached.
    ///
    /// Uses get + insert for portability across cache backends.
    async fn increment_retry_count(&self, cache_key: &str) -> Option<u8> {
        let current = self.message_retry_counts.get(&cache_key.to_string()).await;
        match current {
            Some(count) if count >= MAX_DECRYPT_RETRIES => None,
            Some(count) => {
                let new_count = count + 1;
                self.message_retry_counts
                    .insert(cache_key.to_string(), new_count)
                    .await;
                Some(new_count)
            }
            None => {
                self.message_retry_counts
                    .insert(cache_key.to_string(), 1_u8)
                    .await;
                Some(1)
            }
        }
    }

    /// Helper to generate consistent cache keys for retry logic.
    /// Key format: "{chat}:{msg_id}:{sender}"
    pub(crate) async fn make_retry_cache_key(
        &self,
        chat: &Jid,
        msg_id: &str,
        sender: &Jid,
    ) -> String {
        let chat = self.resolve_encryption_jid(chat).await;
        let sender = self.resolve_encryption_jid(sender).await;
        format!("{}:{}:{}", chat, msg_id, sender)
    }

    /// Spawns a task that sends a retry receipt for a failed decryption.
    ///
    /// This is used when sessions are not found or invalid to request the sender to resend
    /// the message with a PreKeySignalMessage to re-establish the session.
    ///
    /// # Retry Count Tracking
    ///
    /// This method tracks retry counts per message (keyed by `{chat}:{msg_id}:{sender}`)
    /// and stops sending retry receipts after `MAX_DECRYPT_RETRIES` (5) attempts to prevent
    /// infinite retry loops. This matches WhatsApp Web's behavior.
    ///
    /// # PDO Backup
    ///
    /// A PDO (Peer Data Operation) request is spawned only on the FIRST retry attempt.
    /// This asks our primary phone to share the already-decrypted message content.
    /// PDO is NOT spawned on subsequent retries to avoid duplicate requests.
    ///
    /// When max retries is reached, an immediate PDO request is sent as a last resort.
    ///
    /// # Arguments
    /// * `info` - The message info for the failed message
    /// * `reason` - The retry reason code (matches WhatsApp Web's RetryReason enum)
    fn spawn_retry_receipt(self: &Arc<Self>, info: &MessageInfo, reason: RetryReason) {
        let client = Arc::clone(self);
        let info = info.clone();

        self.runtime.spawn(Box::pin(async move {
            let cache_key = client
                .make_retry_cache_key(&info.source.chat, &info.id, &info.source.sender)
                .await;

            // Atomically increment retry count and check if we should continue
            let Some(retry_count) = client.increment_retry_count(&cache_key).await else {
                // Max retries reached
                log::info!(
                    "Max retries ({}) reached for message {} from {} [{:?}]. Sending immediate PDO request.",
                    MAX_DECRYPT_RETRIES,
                    info.id,
                    info.source.sender,
                    reason
                );
                // Send PDO request immediately (no delay) as last resort
                client.spawn_pdo_request_with_options(&info, true);
                return;
            };

            // Log warning for high retry counts (like WhatsApp Web's MessageHighRetryCount)
            if retry_count > HIGH_RETRY_COUNT_THRESHOLD {
                log::warn!(
                    "High retry count ({}) for message {} from {} [{:?}]",
                    retry_count,
                    info.id,
                    info.source.sender,
                    reason
                );
            }

            // Send the retry receipt with the actual retry count and reason
            match client.send_retry_receipt(&info, retry_count, reason).await {
                Ok(()) => {
                    debug!(
                        "Sent retry receipt #{} for message {} from {} [{:?}]",
                        retry_count, info.id, info.source.sender, reason
                    );
                }
                Err(e) => {
                    log::error!(
                        "Failed to send retry receipt #{} for message {} [{:?}]: {:?}",
                        retry_count,
                        info.id,
                        reason,
                        e
                    );
                }
            }

            // Only spawn PDO on the FIRST retry to avoid duplicate requests.
            // The PDO cache also provides deduplication, but this reduces unnecessary work.
            if retry_count == 1 {
                client.spawn_pdo_request(&info);
            }
        })).detach();
    }

    pub(crate) async fn handle_incoming_message(self: Arc<Self>, node: Arc<Node>) {
        let info = match self.parse_message_info(&node).await {
            Ok(info) => Arc::new(info),
            Err(e) => {
                log::warn!("Failed to parse message info: {e:?}");
                return;
            }
        };

        // Newsletters use <plaintext> instead of <enc> because they are not E2E encrypted.
        if info.source.chat.is_newsletter() {
            self.handle_newsletter_message(&node, &info).await;
            return;
        }

        // Determine the JID to use for end-to-end decryption.
        // ... (previous JID resolution comments)
        let sender_encryption_jid = {
            let sender = &info.source.sender;
            let alt = info.source.sender_alt.as_ref();
            let pn_server = wacore_binary::jid::DEFAULT_USER_SERVER;
            let lid_server = wacore_binary::jid::HIDDEN_USER_SERVER;

            if sender.server == lid_server {
                // Sender is already LID - use it directly for session lookup.
                // Also cache the LID-to-PN mapping if PN alt is available.
                if let Some(alt_jid) = alt
                    && alt_jid.server == pn_server
                {
                    if let Err(err) = self
                        .add_lid_pn_mapping(
                            &sender.user,
                            &alt_jid.user,
                            crate::lid_pn_cache::LearningSource::PeerLidMessage,
                        )
                        .await
                    {
                        warn!(
                            "Failed to persist LID-to-PN mapping {} -> {}: {err}",
                            sender.user, alt_jid.user
                        );
                    }
                    debug!(
                        "Cached LID-to-PN mapping: {} -> {}",
                        sender.user, alt_jid.user
                    );
                }
                sender.clone()
            } else if sender.server == pn_server {
                // ... (PN to LID resolution logic)
                if let Some(alt_jid) = alt
                    && alt_jid.server == lid_server
                {
                    if let Err(err) = self
                        .add_lid_pn_mapping(
                            &alt_jid.user,
                            &sender.user,
                            crate::lid_pn_cache::LearningSource::PeerPnMessage,
                        )
                        .await
                    {
                        warn!(
                            "Failed to persist PN-to-LID mapping {} -> {}: {err}",
                            sender.user, alt_jid.user
                        );
                    }
                    debug!(
                        "Cached PN-to-LID mapping: {} -> {}",
                        sender.user, alt_jid.user
                    );

                    Jid {
                        user: alt_jid.user.clone(),
                        server: wacore_binary::jid::cow_server_from_str(lid_server),
                        device: sender.device,
                        agent: sender.agent,
                        integrator: sender.integrator,
                    }
                } else if let Some(lid_user) = self.lid_pn_cache.get_current_lid(&sender.user).await
                {
                    Jid {
                        user: lid_user.clone(),
                        server: wacore_binary::jid::cow_server_from_str(lid_server),
                        device: sender.device,
                        agent: sender.agent,
                        integrator: sender.integrator,
                    }
                } else {
                    sender.clone()
                }
            } else {
                sender.clone()
            }
        };

        let has_unavailable = node.get_optional_child("unavailable").is_some();

        let mut all_enc_nodes = Vec::new();

        let direct_enc_nodes = node.get_children_by_tag("enc");
        all_enc_nodes.extend(direct_enc_nodes);

        let participants = node.get_optional_child_by_tag(&["participants"]);
        if let Some(participants_node) = participants {
            let to_nodes = participants_node.get_children_by_tag("to");
            for to_node in to_nodes {
                let to_jid = match to_node.attrs().optional_string("jid") {
                    Some(jid) => jid.to_string(),
                    None => continue,
                };
                let own_jid = self.get_pn().await;
                if let Some(our_jid) = own_jid
                    && to_jid == our_jid.to_string()
                {
                    let enc_children = to_node.get_children_by_tag("enc");
                    all_enc_nodes.extend(enc_children);
                }
            }
        }

        if all_enc_nodes.is_empty() && !has_unavailable {
            log::warn!(
                "[msg:{}] Received non-newsletter message without <enc> child: {}",
                info.id,
                node.tag
            );
            return;
        }

        if has_unavailable {
            log::debug!(
                "[msg:{}] Message has <unavailable> child, skipping decryption",
                info.id
            );
            return;
        }

        let mut session_enc_nodes = Vec::with_capacity(all_enc_nodes.len());
        let mut group_content_enc_nodes = Vec::with_capacity(all_enc_nodes.len());
        let mut max_sender_retry_count: u8 = 0;
        let mut has_hide_fail = false;

        for &enc_node in &all_enc_nodes {
            // Parse sender retry count (WA Web: e.maybeAttrInt("count") ?? 0)
            // Clamp to MAX_DECRYPT_RETRIES to prevent u64→u8 truncation on unexpected values.
            let sender_count = enc_node
                .attrs()
                .optional_u64("count")
                .map(|c| c.min(MAX_DECRYPT_RETRIES as u64) as u8)
                .unwrap_or(0);
            max_sender_retry_count = max_sender_retry_count.max(sender_count);

            // Parse decrypt-fail attribute (WA Web: e.maybeAttrString("decrypt-fail") === "hide")
            if enc_node
                .attrs
                .get("decrypt-fail")
                .is_some_and(|v| v == "hide")
            {
                has_hide_fail = true;
            }

            let enc_type = match enc_node.attrs().optional_string("type") {
                Some(t) => t,
                None => {
                    log::warn!("Enc node missing 'type' attribute, skipping");
                    continue;
                }
            };

            if let Some(handler) = self
                .custom_enc_handlers
                .read()
                .await
                .get(enc_type.as_ref())
                .cloned()
            {
                let handler_clone = handler;
                let client_clone = self.clone();
                let info_arc = Arc::clone(&info);
                let enc_node_clone = Arc::new(enc_node.clone());
                let enc_type_owned = enc_type.to_string();

                self.runtime
                    .spawn(Box::pin(async move {
                        if let Err(e) = handler_clone
                            .handle(client_clone, &enc_node_clone, &info_arc)
                            .await
                        {
                            log::warn!(
                                "Custom handler for enc type '{}' failed: {e:?}",
                                enc_type_owned
                            );
                        }
                    }))
                    .detach();
                continue;
            }

            // Fall back to built-in handlers
            match enc_type.as_ref() {
                "pkmsg" | "msg" => session_enc_nodes.push(enc_node),
                "skmsg" => group_content_enc_nodes.push(enc_node),
                _ => log::warn!("Unknown enc type: {enc_type}"),
            }
        }

        // WA Web diagnostic: validate skmsg is not first in multi-enc messages.
        // If skmsg comes first, the SKDM (carried in pkmsg/msg) hasn't been processed yet,
        // so the skmsg decryption would fail with NoSenderKey.
        if !session_enc_nodes.is_empty()
            && !group_content_enc_nodes.is_empty()
            && all_enc_nodes
                .first()
                .is_some_and(|n| n.attrs.get("type").is_some_and(|v| v == "skmsg"))
        {
            log::error!(
                "[msg:{}] Protocol violation: skmsg is first in multi-enc message from {}. \
                 Expected pkmsg/msg first (containing SKDM).",
                info.id,
                info.source.sender
            );
        }

        // Determine decrypt fail mode from enc nodes (WA Web: hideFail)
        let decrypt_fail_mode = if has_hide_fail {
            crate::types::events::DecryptFailMode::Hide
        } else {
            crate::types::events::DecryptFailMode::Show
        };

        // Pre-seed retry cache with sender's retry count to avoid redundant retries.
        // Uses max(existing, incoming) so redeliveries with higher counts update the cache,
        // but lower counts don't reset our local counter.
        if max_sender_retry_count > 0 {
            let cache_key = self
                .make_retry_cache_key(&info.source.chat, &info.id, &info.source.sender)
                .await;
            let existing = self.message_retry_counts.get(&cache_key).await.unwrap_or(0);
            if max_sender_retry_count > existing {
                self.message_retry_counts
                    .insert(cache_key, max_sender_retry_count)
                    .await;
            }
            log::debug!(
                "[msg:{}] Sender retry count {} pre-seeded into cache",
                info.id,
                max_sender_retry_count
            );
        }

        // Acquire global processing permit (1 during offline sync, N after).
        // Read generation + clone Arc under the same mutex so the pair is consistent.
        let (generation, semaphore) = match self.message_processing_semaphore.lock() {
            Ok(guard) => (
                self.message_semaphore_generation
                    .load(std::sync::atomic::Ordering::SeqCst),
                guard.clone(),
            ),
            Err(poisoned) => {
                let guard = poisoned.into_inner();
                (
                    self.message_semaphore_generation
                        .load(std::sync::atomic::Ordering::SeqCst),
                    guard.clone(),
                )
            }
        };
        let _global_permit = semaphore.acquire_arc().await;
        // Post-acquire recheck: generation could have changed during the .await
        if generation
            != self
                .message_semaphore_generation
                .load(std::sync::atomic::Ordering::SeqCst)
        {
            log::debug!("Semaphore generation changed during acquire, dropping stale permit");
            return;
        }

        log::debug!(
            "Starting PASS 1: Processing {} session establishment messages (pkmsg/msg)",
            session_enc_nodes.len()
        );

        // Skip session processing for group senders (@c.us, @g.us, @broadcast)
        // Groups don't use 1:1 Signal Protocol sessions
        let is_group_sender = sender_encryption_jid.server.contains(".us")
            || sender_encryption_jid.server.contains("broadcast");

        let (
            session_decrypted_successfully,
            session_had_duplicates,
            session_dispatched_undecryptable,
        ) = if !is_group_sender && !session_enc_nodes.is_empty() {
            self.clone()
                .process_session_enc_batch(
                    &session_enc_nodes,
                    &info,
                    &sender_encryption_jid,
                    decrypt_fail_mode,
                )
                .await
        } else {
            if is_group_sender && !session_enc_nodes.is_empty() {
                log::debug!(
                    "Skipping {} session messages from group sender {}",
                    session_enc_nodes.len(),
                    sender_encryption_jid
                );
            }
            (false, false, false)
        };

        log::debug!(
            "Starting PASS 2: Processing {} group content messages (skmsg)",
            group_content_enc_nodes.len()
        );

        // Only process group content if:
        // 1. There were no session messages (session already exists), OR
        // 2. Session messages were successfully decrypted, OR
        // 3. Session messages were duplicates (already processed, so session exists)
        // Skip only if session messages FAILED to decrypt (not duplicates, not absent).
        // Matches WA Web's `canDecryptNext` pattern: if pkmsg fails with a retriable error,
        // the SKDM it carried is lost, so skmsg will always fail with NoSenderKey — skip it
        // to avoid unnecessary retry receipts. The retry for the pkmsg will cause the sender
        // to resend the entire message including SKDM.
        if !group_content_enc_nodes.is_empty() {
            let should_process_skmsg = session_enc_nodes.is_empty()
                || session_decrypted_successfully
                || session_had_duplicates;

            if should_process_skmsg {
                match self
                    .clone()
                    .process_group_enc_batch(
                        &group_content_enc_nodes,
                        &info,
                        &sender_encryption_jid,
                        decrypt_fail_mode,
                    )
                    .await
                {
                    Ok(()) => {
                        // Processed successfully or handled errors (e.g. sent retry receipt)
                    }
                    Err(e) => {
                        log::warn!("Batch group decrypt encountered error (continuing): {e:?}");
                    }
                }
            } else {
                // Only show warning if session messages actually FAILED (not duplicates)
                if !session_had_duplicates {
                    if info.is_expired_status() {
                        log::debug!(
                            "[msg:{}] Silently dropping expired status from {}",
                            info.id,
                            info.source.sender
                        );
                    } else {
                        warn!(
                            "Skipping skmsg decryption for message {} from {} because pkmsg failed to decrypt.",
                            info.id, info.source.sender
                        );
                        if !session_dispatched_undecryptable {
                            self.dispatch_undecryptable_event(&info, decrypt_fail_mode);
                        }
                    }

                    // Do NOT send a delivery receipt for undecryptable messages.
                    // Per whatsmeow's implementation, delivery receipts are only sent for
                    // successfully decrypted/handled messages. Sending a receipt here would
                    // tell the server we processed it, incrementing the offline counter.
                    // The transport <ack> is sufficient for acknowledgment.
                }
                // If session_had_duplicates is true, we silently skip (no warning, no event)
                // because the message was already processed in a previous session
            }
        } else if !session_decrypted_successfully
            && !session_had_duplicates
            && !session_enc_nodes.is_empty()
        {
            // Edge case: message with only msg/pkmsg that failed to decrypt, no skmsg
            warn!(
                "Message {} from {} failed to decrypt and has no group content. Dispatching UndecryptableMessage event.",
                info.id, info.source.sender
            );
            // Dispatch UndecryptableMessage event for messages that failed to decrypt
            // (This should not cause double-dispatching since process_session_enc_batch
            // already returned dispatched_undecryptable=false for this case)
            self.dispatch_undecryptable_event(&info, decrypt_fail_mode);
            // Do NOT send delivery receipt - transport ack is sufficient
        }

        // Flush cached Signal state to DB (matches WA Web's flushBufferToDiskIfNotMemOnlyMode)
        if let Err(e) = self.flush_signal_cache().await {
            log::error!(
                "Failed to flush signal cache after message {}: {e:?}",
                info.id
            );
        }
    }

    async fn process_session_enc_batch(
        self: Arc<Self>,
        enc_nodes: &[&wacore_binary::node::Node],
        info: &MessageInfo,
        sender_encryption_jid: &Jid,
        decrypt_fail_mode: crate::types::events::DecryptFailMode,
    ) -> (bool, bool, bool) {
        // Returns (any_success, any_duplicate, dispatched_undecryptable)
        use wacore::libsignal::protocol::CiphertextMessage;
        if enc_nodes.is_empty() {
            return (false, false, false);
        }

        // Acquire a per-sender session lock to prevent race conditions when
        // multiple messages from the same sender are processed concurrently.
        // Use the full Signal protocol address string as the lock key so it matches
        // the SignalProtocolStoreAdapter's per-session locks (prevents ratchet counter races).
        let signal_address = sender_encryption_jid.to_protocol_address();

        let session_mutex = self
            .session_locks
            .get_with_by_ref(signal_address.as_str(), async {
                std::sync::Arc::new(async_lock::Mutex::new(()))
            })
            .await;
        let _session_guard = session_mutex.lock().await;

        let mut adapter = SignalProtocolStoreAdapter::new(
            self.persistence_manager.get_device_arc().await,
            self.signal_cache.clone(),
        );
        let mut rng = rand::make_rng::<rand::rngs::StdRng>();
        let mut any_success = false;
        let mut any_duplicate = false;
        let mut dispatched_undecryptable = false;

        for enc_node in enc_nodes {
            let ciphertext: &[u8] = match &enc_node.content {
                Some(wacore_binary::node::NodeContent::Bytes(b)) => b,
                _ => {
                    log::warn!("Enc node has no byte content (batch session)");
                    continue;
                }
            };
            let enc_type = match enc_node.attrs().optional_string("type") {
                Some(t) => t,
                None => {
                    log::warn!("Enc node missing 'type' attribute (batch session)");
                    continue;
                }
            };
            let padding_version = enc_node.attrs().optional_u64("v").unwrap_or(2) as u8;

            let parsed_message = if enc_type.as_ref() == "pkmsg" {
                match PreKeySignalMessage::try_from(ciphertext) {
                    Ok(m) => CiphertextMessage::PreKeySignalMessage(m),
                    Err(e) => {
                        log::error!("Failed to parse PreKeySignalMessage: {e:?}");
                        continue;
                    }
                }
            } else {
                match SignalMessage::try_from(ciphertext) {
                    Ok(m) => CiphertextMessage::SignalMessage(m),
                    Err(e) => {
                        log::error!("Failed to parse SignalMessage: {e:?}");
                        continue;
                    }
                }
            };

            if enc_type.as_ref() == "pkmsg" {
                // FLAGGED FOR DEBUGGING: "Bad Mac" Reproducibility
                #[cfg(feature = "debug-snapshots")]
                {
                    use base64::prelude::*;
                    let payload = serde_json::json!({
                        "id": info.id,
                        "sender_jid": sender_encryption_jid.to_string(),
                        "timestamp": info.timestamp,
                        "enc_type": enc_type,
                        "payload_base64": BASE64_STANDARD.encode(ciphertext),
                    });

                    let content_bytes = serde_json::to_vec_pretty(&payload).unwrap_or_default();

                    if let Err(e) = self
                        .persistence_manager
                        .create_snapshot(&format!("pre_pkmsg_{}", info.id), Some(&content_bytes))
                        .await
                    {
                        log::warn!("Failed to create snapshot for pkmsg: {}", e);
                    }
                }
                #[cfg(not(feature = "debug-snapshots"))]
                {
                    // No-op if disabled
                }
            }

            let decrypt_res = message_decrypt(
                &parsed_message,
                &signal_address,
                &mut adapter.session_store,
                &mut adapter.identity_store,
                &mut adapter.pre_key_store,
                &adapter.signed_pre_key_store,
                &mut rng,
                UsePQRatchet::No,
            )
            .await;

            match decrypt_res {
                Ok(padded_plaintext) => {
                    any_success = true;
                    if let Err(e) = self
                        .clone()
                        .handle_decrypted_plaintext(
                            &enc_type,
                            &padded_plaintext,
                            padding_version,
                            info,
                        )
                        .await
                    {
                        log::warn!("Failed processing plaintext (batch session): {e:?}");
                    }
                }
                Err(e) => {
                    // Handle DuplicatedMessage: This is expected when messages are redelivered during reconnection
                    if let SignalProtocolError::DuplicatedMessage(chain, counter) = e {
                        log::debug!(
                            "Skipping already-processed message from {} (chain {}, counter {}). This is normal during reconnection.",
                            info.source.sender,
                            chain,
                            counter
                        );
                        // Mark that we saw a duplicate so we can skip skmsg without showing error
                        any_duplicate = true;
                        continue;
                    }
                    // Handle UntrustedIdentity: This happens when a user re-installs WhatsApp or changes devices.
                    // The Signal Protocol's security policy rejects messages from new identity keys by default.
                    // We handle this by clearing the old identity (to trust the new one), then retrying decryption.
                    // IMPORTANT: We do NOT delete the session! When the PreKeySignalMessage is processed,
                    // libsignal's `promote_state` will archive the old session as a "previous state".
                    // This allows us to decrypt any in-flight messages that were encrypted with the old session.
                    if let SignalProtocolError::UntrustedIdentity(ref address) = e {
                        log::warn!(
                            "[msg:{}] Received message from untrusted identity: {}. This typically means the sender re-installed WhatsApp or changed their device. Clearing old identity to trust new key (keeping session for in-flight messages).",
                            info.id,
                            address
                        );

                        // Delete the old, untrusted identity through the signal cache.
                        // NOTE: We intentionally do NOT delete the session here. The session will be
                        // archived (not deleted) when the new PreKeySignalMessage is processed,
                        // allowing decryption of any in-flight messages encrypted with the old session.
                        self.signal_cache.delete_identity(address).await;
                        // Flush immediately so the backend is updated BEFORE the retry decrypt below.
                        // Device::is_trusted_identity reads from backend, not cache.
                        if let Err(e) = self.flush_signal_cache().await {
                            log::warn!("Failed to flush identity deletion for {}: {e:?}", address);
                            continue;
                        }
                        log::info!(
                            "Cleared old identity for {} from cache and backend",
                            address
                        );

                        // Re-attempt decryption with the new identity
                        log::info!(
                            "[msg:{}] Retrying message decryption for {} after clearing untrusted identity",
                            info.id,
                            address
                        );

                        let retry_decrypt_res = message_decrypt(
                            &parsed_message,
                            &signal_address,
                            &mut adapter.session_store,
                            &mut adapter.identity_store,
                            &mut adapter.pre_key_store,
                            &adapter.signed_pre_key_store,
                            &mut rng,
                            UsePQRatchet::No,
                        )
                        .await;

                        match retry_decrypt_res {
                            Ok(padded_plaintext) => {
                                log::debug!(
                                    "[msg:{}] Successfully decrypted message from {} after handling untrusted identity",
                                    info.id,
                                    address
                                );
                                any_success = true;
                                if let Err(e) = self
                                    .clone()
                                    .handle_decrypted_plaintext(
                                        &enc_type,
                                        &padded_plaintext,
                                        padding_version,
                                        info,
                                    )
                                    .await
                                {
                                    log::warn!(
                                        "Failed processing plaintext after identity retry: {e:?}"
                                    );
                                }
                            }
                            Err(retry_err) => {
                                // Handle DuplicatedMessage in retry path: This commonly happens during reconnection
                                // when the same message is redelivered by the server after we already processed it.
                                // The first attempt triggered UntrustedIdentity, we cleared the session, but meanwhile
                                // another message from the same sender re-established the session and consumed the counter.
                                // This is benign - the message was already successfully processed.
                                if let SignalProtocolError::DuplicatedMessage(chain, counter) =
                                    retry_err
                                {
                                    log::debug!(
                                        "Message from {} was already processed (chain {}, counter {}) - detected during untrusted identity retry. This is normal during reconnection.",
                                        address,
                                        chain,
                                        counter
                                    );
                                    any_duplicate = true;
                                } else if matches!(retry_err, SignalProtocolError::InvalidPreKeyId)
                                {
                                    // InvalidPreKeyId after identity change means the sender is using
                                    // an old prekey that we no longer have. This typically happens when:
                                    // 1. The sender reinstalled WhatsApp and cached our old prekey bundle
                                    // 2. The prekey they're using has been consumed or rotated out
                                    //
                                    // Solution: Send a retry receipt with a fresh prekey so the sender
                                    // can establish a new session and resend the message.
                                    log::warn!(
                                        "[msg:{}] Decryption failed for {} due to InvalidPreKeyId after identity change. \
                                         The sender is using an old prekey we no longer have. \
                                         Sending retry receipt with fresh keys.",
                                        info.id,
                                        address
                                    );

                                    // Send retry receipt so the sender fetches our new prekey bundle
                                    dispatched_undecryptable = self.handle_decrypt_failure(
                                        info,
                                        RetryReason::InvalidKeyId,
                                        decrypt_fail_mode,
                                    );
                                } else {
                                    log::error!(
                                        "[msg:{}] Decryption failed even after clearing untrusted identity for {}: {:?}",
                                        info.id,
                                        address,
                                        retry_err
                                    );
                                    // Send retry receipt so the sender resends with a PreKeySignalMessage
                                    // to establish a new session with the new identity
                                    dispatched_undecryptable = self.handle_decrypt_failure(
                                        info,
                                        RetryReason::InvalidKey,
                                        decrypt_fail_mode,
                                    );
                                }
                            }
                        }
                        continue;
                    }
                    // Handle SessionNotFound gracefully - send retry receipt to request session establishment
                    if let SignalProtocolError::SessionNotFound(_) = e {
                        warn!(
                            "[msg:{}] No session found for {} message from {}. Sending retry receipt to request session establishment.",
                            info.id, enc_type, info.source.sender
                        );
                        // Send retry receipt so the sender resends with a PreKeySignalMessage
                        dispatched_undecryptable = self.handle_decrypt_failure(
                            info,
                            RetryReason::NoSession,
                            decrypt_fail_mode,
                        );
                        continue;
                    } else if matches!(e, SignalProtocolError::InvalidMessage(_, _)) {
                        // InvalidMessage typically means MAC verification failed or session is out of sync.
                        // This happens when the sender's session state diverged from ours (e.g., they reinstalled).
                        // We need to:
                        // 1. Delete the stale session so a new one can be established
                        // 2. Send a retry receipt so the sender resends with a PreKeySignalMessage
                        log::warn!(
                            "[msg:{}] Decryption failed for {} message from {} due to InvalidMessage (likely MAC failure). \
                             Deleting stale session and sending retry receipt.",
                            info.id,
                            enc_type,
                            info.source.sender
                        );

                        // Delete the stale session from the signal cache.
                        // IMPORTANT: Must go through the cache, not directly to the backend!
                        // Going to the backend directly leaves the stale session in the cache,
                        // which causes retry messages to also fail (they'd load the stale session).
                        self.signal_cache.delete_session(&signal_address).await;
                        log::info!(
                            "Deleted stale session for {} from cache to allow re-establishment",
                            signal_address
                        );

                        // Send retry receipt so the sender resends with a PreKeySignalMessage
                        dispatched_undecryptable = self.handle_decrypt_failure(
                            info,
                            RetryReason::InvalidMessage,
                            decrypt_fail_mode,
                        );
                        continue;
                    } else if matches!(e, SignalProtocolError::InvalidPreKeyId) {
                        // InvalidPreKeyId means the sender is using a PreKey ID that we don't have.
                        // This typically happens when:
                        // 1. We were offline for a long time
                        // 2. The sender established a session with us using a prekey from the server
                        // 3. We never received the initial session-establishing message
                        // 4. Now we're receiving messages with counters 3, 4, 5... referencing that prekey
                        //
                        // The sender thinks they have a valid session, but we never had it.
                        // We need to send a retry receipt with fresh prekeys so the sender can:
                        // 1. Delete their old session
                        // 2. Fetch our new prekeys from the retry receipt
                        // 3. Create a NEW session and resend with counter 0
                        log::warn!(
                            "[msg:{}] Decryption failed for {} message from {} due to InvalidPreKeyId. \
                             Sender is using a prekey we don't have (likely session established while offline). \
                             Sending retry receipt with fresh prekeys.",
                            info.id,
                            enc_type,
                            info.source.sender
                        );

                        // Send retry receipt with fresh prekeys
                        dispatched_undecryptable = self.handle_decrypt_failure(
                            info,
                            RetryReason::InvalidKeyId,
                            decrypt_fail_mode,
                        );
                        continue;
                    } else {
                        // For other unexpected errors, just log them
                        log::error!(
                            "[msg:{}] Batch session decrypt failed (type: {}) from {}: {:?}",
                            info.id,
                            enc_type,
                            info.source.sender,
                            e
                        );
                        continue;
                    }
                }
            }
        }
        (any_success, any_duplicate, dispatched_undecryptable)
    }

    async fn process_group_enc_batch(
        self: Arc<Self>,
        enc_nodes: &[&wacore_binary::node::Node],
        info: &MessageInfo,
        _sender_encryption_jid: &Jid,
        _decrypt_fail_mode: crate::types::events::DecryptFailMode,
    ) -> Result<(), DecryptionError> {
        if enc_nodes.is_empty() {
            return Ok(());
        }
        let device_arc = self.persistence_manager.get_device_arc().await;
        // Use the signal cache adapter for group decryption so sender keys are read/written
        // through the cache, keeping it consistent with SKDM processing.
        let mut adapter = SignalProtocolStoreAdapter::new(device_arc, self.signal_cache.clone());

        for enc_node in enc_nodes {
            let ciphertext: &[u8] = match &enc_node.content {
                Some(wacore_binary::node::NodeContent::Bytes(b)) => b,
                _ => {
                    log::warn!("Enc node has no byte content (batch group)");
                    continue;
                }
            };
            let padding_version = enc_node.attrs().optional_u64("v").unwrap_or(2) as u8;

            // CRITICAL: Use info.source.sender (display JID) for sender key operations, NOT sender_encryption_jid.
            // The sender key is stored under the sender's display JID (e.g., LID), while sender_encryption_jid
            // is the phone number used for E2E session decryption only.
            // Using sender_encryption_jid here causes "No sender key state" errors for self-sent LID messages.
            let sender_address = info.source.sender.to_protocol_address();
            let sender_key_name =
                SenderKeyName::new(info.source.chat.to_string(), sender_address.to_string());

            log::debug!(
                "Looking up sender key for group {} with sender address {} (from sender JID: {})",
                info.source.chat,
                sender_address,
                info.source.sender
            );

            let decrypt_result =
                group_decrypt(ciphertext, &mut adapter.sender_key_store, &sender_key_name).await;

            match decrypt_result {
                Ok(padded_plaintext) => {
                    if let Err(e) = self
                        .clone()
                        .handle_decrypted_plaintext(
                            "skmsg",
                            &padded_plaintext,
                            padding_version,
                            info,
                        )
                        .await
                    {
                        log::warn!("Failed processing group plaintext (batch): {e:?}");
                    }
                }
                Err(SignalProtocolError::DuplicatedMessage(iteration, counter)) => {
                    log::debug!(
                        "Skipping already-processed sender key message from {} in group {} (iteration {}, counter {}). This is normal during reconnection.",
                        info.source.sender,
                        info.source.chat,
                        iteration,
                        counter
                    );
                    // This is expected when messages are redelivered, just continue silently
                }
                Err(SignalProtocolError::NoSenderKeyState(msg)) => {
                    if info.is_expired_status() {
                        log::debug!(
                            "[msg:{}] Skipping retry for expired status from {}",
                            info.id,
                            info.source.sender
                        );
                        continue;
                    }

                    // No sender key for this group/sender — the SKDM was never received
                    // (sender thinks we have it from a previous status/session).
                    // Send retry receipt to ask sender to re-distribute SKDM.
                    warn!(
                        "No sender key state for group message [msg:{}] from {}: {}. Sending retry receipt.",
                        info.id, info.source.sender, msg
                    );
                    self.spawn_retry_receipt(info, RetryReason::NoSession);
                }
                Err(e) => {
                    if info.is_expired_status() {
                        log::debug!(
                            "[msg:{}] Ignoring decrypt error for expired status from {}: {:?}",
                            info.id,
                            info.source.sender,
                            e
                        );
                        continue;
                    }

                    log::error!(
                        "Group batch decrypt failed [msg:{}] for group {} sender {}: {:?}",
                        info.id,
                        sender_key_name.group_id(),
                        sender_key_name.sender_id(),
                        e
                    );
                }
            }
        }
        Ok(())
    }

    async fn handle_decrypted_plaintext(
        self: Arc<Self>,
        enc_type: &str,
        padded_plaintext: &[u8],
        padding_version: u8,
        info: &MessageInfo,
    ) -> Result<(), anyhow::Error> {
        let original_msg = wacore::messages::decode_plaintext(padded_plaintext, padding_version)?;
        log::debug!(
            "[msg:{}] Successfully decrypted message from {}: type={} [batch path]",
            info.id,
            info.source.sender,
            enc_type
        );

        // Validate DSM presence against sender identity
        // (WAWebHandleMsgError.DeviceSentMessageError)
        if original_msg.device_sent_message.is_some() && !info.source.is_from_me {
            warn!(
                "[msg:{}] DeviceSentMessage present but sender {} is not self",
                info.id, info.source.sender,
            );
        }

        // Unwrap DeviceSentMessage wrapper (self-sent messages synced from
        // the primary device). The actual content (reactions, text, etc.)
        // is nested inside device_sent_message.message and must be
        // extracted before protocol checks or dispatch.
        let mut msg = wacore::messages::unwrap_device_sent(original_msg);

        // Post-decryption logic (SKDM, sync keys, etc.)
        if let Some(skdm) = &msg.sender_key_distribution_message
            && let Some(axolotl_bytes) = &skdm.axolotl_sender_key_distribution_message
        {
            self.handle_sender_key_distribution_message(
                &info.source.chat,
                &info.source.sender,
                axolotl_bytes,
            )
            .await;
        }

        if let Some(protocol_msg) = &msg.protocol_message
            && let Some(keys) = &protocol_msg.app_state_sync_key_share
        {
            self.handle_app_state_sync_key_share(keys).await;
        }

        if let Some(protocol_msg) = &msg.protocol_message
            && let Some(pdo_response) = &protocol_msg.peer_data_operation_request_response_message
        {
            self.handle_pdo_response(pdo_response, info).await;
        }

        // Note: msg might be modified by take() below
        let history_sync_taken = msg
            .protocol_message
            .as_mut()
            .and_then(|pm| pm.history_sync_notification.take());

        if let Some(history_sync) = history_sync_taken {
            self.handle_history_sync(info.id.clone(), history_sync)
                .await;
        }

        // Skip dispatch for messages that only carry sender key distribution
        // (protocol-level key exchange) with no user-visible content.
        // These arrive as a separate pkmsg enc node alongside the actual
        // group message (skmsg) and would otherwise surface as "unknown".
        if wacore::messages::is_sender_key_distribution_only(&msg) {
            log::debug!(
                "[msg:{}] Skipping event dispatch for sender key distribution message",
                info.id
            );
        } else {
            self.dispatch_parsed_message(msg, info);
        }
        Ok(())
    }

    pub(crate) async fn parse_message_info(
        &self,
        node: &Node,
    ) -> Result<MessageInfo, anyhow::Error> {
        let device_snapshot = self.persistence_manager.get_device_snapshot().await;
        let own_jid = device_snapshot.pn.clone().unwrap_or_default();
        let own_lid = device_snapshot.lid.clone();
        wacore::messages::parse_message_info(node, &own_jid, own_lid.as_ref())
    }

    pub(crate) async fn handle_app_state_sync_key_share(
        &self,
        keys: &wa::message::AppStateSyncKeyShare,
    ) {
        struct KeyComponents<'a> {
            key_id: &'a [u8],
            data: &'a [u8],
            fingerprint_bytes: Vec<u8>,
            timestamp: i64,
        }

        /// Extract components from an AppStateSyncKey for storage.
        fn extract_key_components(key: &wa::message::AppStateSyncKey) -> Option<KeyComponents<'_>> {
            let key_id = key.key_id.as_ref()?.key_id.as_ref()?;
            let key_data = key.key_data.as_ref()?;
            let fingerprint = key_data.fingerprint.as_ref()?;
            let data = key_data.key_data.as_ref()?;
            Some(KeyComponents {
                key_id,
                data,
                fingerprint_bytes: fingerprint.encode_to_vec(),
                timestamp: key_data.timestamp(),
            })
        }

        let device_snapshot = self.persistence_manager.get_device_snapshot().await;
        let key_store = device_snapshot.backend.clone();

        let mut stored_count = 0;
        let mut failed_count = 0;

        for key in &keys.keys {
            if let Some(components) = extract_key_components(key) {
                let new_key = crate::store::traits::AppStateSyncKey {
                    key_data: components.data.to_vec(),
                    fingerprint: components.fingerprint_bytes,
                    timestamp: components.timestamp,
                };

                if let Err(e) = key_store.set_sync_key(components.key_id, new_key).await {
                    log::error!(
                        "Failed to store app state sync key {:?}: {:?}",
                        hex::encode(components.key_id),
                        e
                    );
                    failed_count += 1;
                } else {
                    stored_count += 1;
                }
            }
        }

        if stored_count > 0 || failed_count > 0 {
            log::info!(
                target: "Client/AppState",
                "Processed app state key share: {} stored, {} failed.",
                stored_count,
                failed_count
            );
        }

        // Notify any waiters (initial full sync) that at least one key share was processed.
        if stored_count > 0
            && !self
                .initial_app_state_keys_received
                .swap(true, std::sync::atomic::Ordering::Relaxed)
        {
            // First time setting; notify any waiters
            self.initial_keys_synced_notifier.notify(usize::MAX);
        }
    }

    async fn handle_sender_key_distribution_message(
        self: &Arc<Self>,
        group_jid: &Jid,
        sender_jid: &Jid,
        axolotl_bytes: &[u8],
    ) {
        let skdm = match SenderKeyDistributionMessage::try_from(axolotl_bytes) {
            Ok(msg) => msg,
            Err(e1) => match wa::SenderKeyDistributionMessage::decode(axolotl_bytes) {
                Ok(go_msg) => {
                    let (Some(signing_key), Some(id), Some(iteration), Some(chain_key)) = (
                        go_msg.signing_key.as_ref(),
                        go_msg.id,
                        go_msg.iteration,
                        go_msg.chain_key.as_ref(),
                    ) else {
                        log::warn!(
                            "Go SKDM from {} missing required fields (signing_key={}, id={}, iteration={}, chain_key={})",
                            sender_jid,
                            go_msg.signing_key.is_some(),
                            go_msg.id.is_some(),
                            go_msg.iteration.is_some(),
                            go_msg.chain_key.is_some()
                        );
                        return;
                    };
                    let chain_key_arr: [u8; 32] = match chain_key.as_slice().try_into() {
                        Ok(arr) => arr,
                        Err(_) => {
                            log::error!(
                                "Invalid chain_key length {} from Go SKDM from {}",
                                chain_key.len(),
                                sender_jid
                            );
                            return;
                        }
                    };
                    match SignalPublicKey::from_djb_public_key_bytes(signing_key) {
                        Ok(pub_key) => {
                            match SenderKeyDistributionMessage::new(
                                SENDERKEY_MESSAGE_CURRENT_VERSION,
                                id,
                                iteration,
                                chain_key_arr,
                                pub_key,
                            ) {
                                Ok(skdm) => skdm,
                                Err(e) => {
                                    log::error!(
                                        "Failed to construct SKDM from Go format from {}: {:?} (original parse error: {:?})",
                                        sender_jid,
                                        e,
                                        e1
                                    );
                                    return;
                                }
                            }
                        }
                        Err(e) => {
                            log::error!(
                                "Failed to parse public key from Go SKDM for {}: {:?} (original parse error: {:?})",
                                sender_jid,
                                e,
                                e1
                            );
                            return;
                        }
                    }
                }
                Err(e2) => {
                    log::error!(
                        "Failed to parse SenderKeyDistributionMessage (standard and Go fallback) from {}: primary: {:?}, fallback: {:?}",
                        sender_jid,
                        e1,
                        e2
                    );
                    return;
                }
            },
        };

        let device_arc = self.persistence_manager.get_device_arc().await;

        let sender_address = sender_jid.to_protocol_address();

        let sender_key_name = SenderKeyName::new(group_jid.to_string(), sender_address.to_string());

        // Route through the signal cache adapter so the sender key is immediately visible
        // in the cache for subsequent group_decrypt calls within the same message batch.
        let mut adapter = SignalProtocolStoreAdapter::new(device_arc, self.signal_cache.clone());

        if let Err(e) = process_sender_key_distribution_message(
            &sender_key_name,
            &skdm,
            &mut adapter.sender_key_store,
        )
        .await
        {
            log::error!(
                "Failed to process SenderKeyDistributionMessage from {}: {:?}",
                sender_jid,
                e
            );
        } else {
            log::debug!(
                "Successfully processed sender key distribution for group {} from {}",
                group_jid,
                sender_jid
            );
        }
    }
}

/// Unwraps a `DeviceSentMessage` wrapper, returning the inner message with
/// merged `message_context_info`.
///
/// Self-sent messages synced from the primary device arrive with the actual
/// content (reactions, text, etc.) nested inside `device_sent_message.message`.
/// This extracts the inner message when present, merges `MessageContextInfo`
/// from outer and inner following WhatsApp Web's
/// `WAWebDeviceSentMessageProtoUtils.unwrapDeviceSentMessage` logic, or returns
/// the original message unchanged when there is no wrapper or the wrapper has
/// no inner message.
/// Re-export from wacore for backwards compatibility (used by tests via `super::*`).
#[cfg(test)]
fn unwrap_device_sent(msg: wa::Message) -> wa::Message {
    wacore::messages::unwrap_device_sent(msg)
}

/// Re-export from wacore for backwards compatibility (used by tests via `super::*`).
#[cfg(test)]
fn is_sender_key_distribution_only(msg: &wa::Message) -> bool {
    wacore::messages::is_sender_key_distribution_only(msg)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::SqliteStore;
    use crate::store::persistence_manager::PersistenceManager;
    use crate::test_utils::MockHttpClient;
    use crate::types::message::EditAttribute;
    use std::sync::Arc;
    use wacore_binary::builder::NodeBuilder;
    use wacore_binary::jid::{Jid, SERVER_JID};

    fn mock_transport() -> Arc<dyn crate::transport::TransportFactory> {
        Arc::new(crate::transport::mock::MockTransportFactory::new())
    }

    fn mock_http_client() -> Arc<dyn crate::http::HttpClient> {
        Arc::new(MockHttpClient)
    }

    #[tokio::test]
    async fn test_parse_message_info_for_status_broadcast() {
        let backend = Arc::new(
            SqliteStore::new("file:memdb_status_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let participant_jid_str = "556899336555:42@s.whatsapp.net";
        let status_broadcast_jid_str = "status@broadcast";

        let node = NodeBuilder::new("message")
            .attr("from", status_broadcast_jid_str)
            .attr("id", "8A8CCCC7E6E466D9EE8CA11A967E485A")
            .attr("participant", participant_jid_str)
            .attr("t", "1759295366")
            .attr("type", "media")
            .build();

        let info = client
            .parse_message_info(&node)
            .await
            .expect("parse_message_info should not fail");

        let expected_sender: Jid = participant_jid_str
            .parse()
            .expect("test JID should be valid");
        let expected_chat: Jid = status_broadcast_jid_str
            .parse()
            .expect("test JID should be valid");

        assert_eq!(
            info.source.sender, expected_sender,
            "The sender should be the 'participant' JID, not 'status@broadcast'"
        );
        assert_eq!(
            info.source.chat, expected_chat,
            "The chat should be 'status@broadcast'"
        );
        assert!(
            info.source.is_group,
            "Broadcast messages should be treated as group-like"
        );
    }

    #[tokio::test]
    async fn test_process_session_enc_batch_handles_session_not_found_gracefully() {
        use wacore::libsignal::protocol::{IdentityKeyPair, KeyPair, SignalMessage};

        let backend = Arc::new(
            SqliteStore::new("file:memdb_graceful_fail?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let sender_jid: Jid = "1234567890@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");
        let info = MessageInfo {
            source: crate::types::message::MessageSource {
                sender: sender_jid.clone(),
                chat: sender_jid.clone(),
                ..Default::default()
            },
            ..Default::default()
        };

        // Create a valid but undecryptable SignalMessage
        let dummy_key = [0u8; 32];
        let sender_ratchet =
            KeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>()).public_key;
        let sender_identity_pair =
            IdentityKeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>());
        let receiver_identity_pair =
            IdentityKeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>());
        let signal_message = SignalMessage::new(
            4,
            &dummy_key,
            sender_ratchet,
            0,
            0,
            b"test",
            sender_identity_pair.identity_key(),
            receiver_identity_pair.identity_key(),
        )
        .expect("SignalMessage::new should succeed with valid inputs");

        let enc_node = NodeBuilder::new("enc")
            .attr("type", "msg")
            .bytes(signal_message.serialized().to_vec())
            .build();
        let enc_nodes = vec![&enc_node];

        // With SessionNotFound, should return (false, false, true) - no success, no dupe, dispatched event
        let (success, had_duplicates, dispatched) = client
            .process_session_enc_batch(
                &enc_nodes,
                &info,
                &sender_jid,
                crate::types::events::DecryptFailMode::Show,
            )
            .await;

        assert!(
            !success && !had_duplicates && dispatched,
            "process_session_enc_batch should return (false, false, true) when SessionNotFound occurs and dispatches event"
        );
    }

    #[tokio::test]
    async fn test_handle_incoming_message_skips_skmsg_after_msg_failure() {
        use wacore::libsignal::protocol::{IdentityKeyPair, KeyPair, SignalMessage};

        let backend = Arc::new(
            SqliteStore::new("file:memdb_skip_skmsg_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let sender_jid: Jid = "1234567890@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");
        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");

        // Create msg + skmsg node; msg will fail (no session), so skmsg should be skipped
        let dummy_key = [0u8; 32];
        let sender_ratchet =
            KeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>()).public_key;
        let sender_identity_pair =
            IdentityKeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>());
        let receiver_identity_pair =
            IdentityKeyPair::generate(&mut rand::make_rng::<rand::rngs::StdRng>());
        let signal_message = SignalMessage::new(
            4,
            &dummy_key,
            sender_ratchet,
            0,
            0,
            b"test",
            sender_identity_pair.identity_key(),
            receiver_identity_pair.identity_key(),
        )
        .expect("SignalMessage::new should succeed with valid inputs");

        let msg_node = NodeBuilder::new("enc")
            .attr("type", "msg")
            .bytes(signal_message.serialized().to_vec())
            .build();

        let skmsg_node = NodeBuilder::new("enc")
            .attr("type", "skmsg")
            .bytes(vec![4, 5, 6])
            .build();

        let message_node = Arc::new(
            NodeBuilder::new("message")
                .attr("from", group_jid)
                .attr("participant", sender_jid)
                .attr("id", "test-id-123")
                .attr("t", "12345")
                .children(vec![msg_node, skmsg_node])
                .build(),
        );

        // Should not panic or retry loop - skmsg is skipped after msg failure
        client.handle_incoming_message(message_node).await;
    }

    /// Test case for reproducing sender key JID mismatch in LID group messages
    ///
    /// Problem:
    /// - When we process sender key distribution from a self-sent LID message, we store it under the LID JID
    /// - But when we try to decrypt the group content (skmsg), we look it up using the phone number JID
    /// - This causes "No sender key state" errors even though we just processed the sender key!
    ///
    /// This test verifies the fix by:
    /// 1. Creating a sender key and storing it under the LID address (mimicking SKDM processing)
    /// 2. Attempting retrieval with phone number address (the bug) - should fail
    /// 3. Attempting retrieval with LID address (the fix) - should succeed
    #[tokio::test]
    async fn test_self_sent_lid_group_message_sender_key_mismatch() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::libsignal::protocol::{
            SenderKeyStore, create_sender_key_distribution_message,
            process_sender_key_distribution_message,
        };
        use wacore::libsignal::store::sender_key_name::SenderKeyName;
        let backend = Arc::new(
            SqliteStore::new("file:memdb_sender_key_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (_client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let own_lid: Jid = "100000000000001.1:75@lid"
            .parse()
            .expect("test JID should be valid");
        let own_phone: Jid = "15551234567:75@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");
        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");

        // Create SKDM using LID address (mimics handle_sender_key_distribution_message)
        let lid_protocol_address = own_lid.to_protocol_address();
        let lid_sender_key_name =
            SenderKeyName::new(group_jid.to_string(), lid_protocol_address.to_string());

        let device_arc = pm.get_device_arc().await;
        let skdm = {
            let mut device_guard = device_arc.write().await;
            create_sender_key_distribution_message(
                &lid_sender_key_name,
                &mut *device_guard,
                &mut rand::make_rng::<rand::rngs::StdRng>(),
            )
            .await
            .expect("Failed to create SKDM")
        };

        {
            let mut device_guard = device_arc.write().await;
            process_sender_key_distribution_message(
                &lid_sender_key_name,
                &skdm,
                &mut *device_guard,
            )
            .await
            .expect("Failed to process SKDM with LID address");
        }

        // Try to retrieve using PHONE NUMBER address (THE BUG)
        let phone_protocol_address = own_phone.to_protocol_address();
        let phone_sender_key_name =
            SenderKeyName::new(group_jid.to_string(), phone_protocol_address.to_string());

        let phone_lookup_result = {
            let mut device_guard = device_arc.write().await;
            device_guard.load_sender_key(&phone_sender_key_name).await
        };

        assert!(
            phone_lookup_result
                .expect("lookup should not error")
                .is_none(),
            "Sender key should NOT be found when looking up with phone number address (demonstrates the bug)"
        );

        // Try to retrieve using LID address (THE FIX)
        let lid_lookup_result = {
            let mut device_guard = device_arc.write().await;
            device_guard.load_sender_key(&lid_sender_key_name).await
        };

        assert!(
            lid_lookup_result
                .expect("lookup should not error")
                .is_some(),
            "Sender key SHOULD be found when looking up with LID address (same as storage)"
        );
    }

    /// Test that sender key consistency is maintained for multiple LID participants
    ///
    /// Edge case: Group with multiple LID participants, each should have their own
    /// sender key stored under their LID address, not mixed up with phone numbers.
    #[tokio::test]
    async fn test_multiple_lid_participants_sender_key_isolation() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::libsignal::protocol::{
            SenderKeyStore, create_sender_key_distribution_message,
            process_sender_key_distribution_message,
        };
        use wacore::libsignal::store::sender_key_name::SenderKeyName;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_multi_lid_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let transport_factory = Arc::new(crate::transport::mock::MockTransportFactory::new());
        let (_client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            transport_factory,
            mock_http_client(),
            None,
        )
        .await;

        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");

        // Simulate three LID participants
        let participants = vec![
            ("100000000000001.1:75@lid", "15551234567:75@s.whatsapp.net"),
            ("987654321000000.2:42@lid", "551234567890:42@s.whatsapp.net"),
            ("111222333444555.3:10@lid", "559876543210:10@s.whatsapp.net"),
        ];

        let device_arc = pm.get_device_arc().await;

        // Create and store sender keys for each participant under their LID address
        for (lid_str, _phone_str) in &participants {
            let lid_jid: Jid = lid_str.parse().expect("test JID should be valid");
            let lid_protocol_address = lid_jid.to_protocol_address();
            let lid_sender_key_name =
                SenderKeyName::new(group_jid.to_string(), lid_protocol_address.to_string());

            let skdm = {
                let mut device_guard = device_arc.write().await;
                create_sender_key_distribution_message(
                    &lid_sender_key_name,
                    &mut *device_guard,
                    &mut rand::make_rng::<rand::rngs::StdRng>(),
                )
                .await
                .expect("Failed to create SKDM")
            };

            let mut device_guard = device_arc.write().await;
            process_sender_key_distribution_message(
                &lid_sender_key_name,
                &skdm,
                &mut *device_guard,
            )
            .await
            .expect("Failed to process SKDM");
        }

        // Verify each participant's sender key can be retrieved using their LID address
        for (lid_str, phone_str) in &participants {
            let lid_jid: Jid = lid_str.parse().expect("test JID should be valid");
            let phone_jid: Jid = phone_str.parse().expect("test JID should be valid");

            let lid_protocol_address = lid_jid.to_protocol_address();
            let phone_protocol_address = phone_jid.to_protocol_address();

            let lid_sender_key_name =
                SenderKeyName::new(group_jid.to_string(), lid_protocol_address.to_string());
            let phone_sender_key_name =
                SenderKeyName::new(group_jid.to_string(), phone_protocol_address.to_string());

            // Should find with LID address
            let lid_lookup = {
                let mut device_guard = device_arc.write().await;
                device_guard.load_sender_key(&lid_sender_key_name).await
            };
            assert!(
                lid_lookup.expect("lookup should not error").is_some(),
                "Sender key for {} should be found with LID address",
                lid_str
            );

            // Should NOT find with phone number address (the bug)
            let phone_lookup = {
                let mut device_guard = device_arc.write().await;
                device_guard.load_sender_key(&phone_sender_key_name).await
            };
            assert!(
                phone_lookup.expect("lookup should not error").is_none(),
                "Sender key for {} should NOT be found with phone number address",
                lid_str
            );
        }
    }

    /// Test that LID JID parsing handles various edge cases correctly
    ///
    /// Edge cases:
    /// - LID with multiple dots in user portion
    /// - LID with device numbers
    /// - LID without device numbers
    #[test]
    fn test_lid_jid_parsing_edge_cases() {
        use wacore_binary::jid::Jid;

        // Single dot in user portion
        let lid1: Jid = "100000000000001.1:75@lid"
            .parse()
            .expect("test JID should be valid");
        assert_eq!(lid1.user, "100000000000001.1");
        assert_eq!(lid1.device, 75);
        assert_eq!(lid1.agent, 0);

        // Multiple dots in user portion (extreme edge case)
        let lid2: Jid = "123.456.789.0:50@lid"
            .parse()
            .expect("test JID should be valid");
        assert_eq!(lid2.user, "123.456.789.0");
        assert_eq!(lid2.device, 50);
        assert_eq!(lid2.agent, 0);

        // No device number (device 0)
        let lid3: Jid = "987654321000000.5@lid"
            .parse()
            .expect("test JID should be valid");
        assert_eq!(lid3.user, "987654321000000.5");
        assert_eq!(lid3.device, 0);
        assert_eq!(lid3.agent, 0);

        // Very long user portion with dot
        let lid4: Jid = "111222333444555666777.999:1@lid"
            .parse()
            .expect("test JID should be valid");
        assert_eq!(lid4.user, "111222333444555666777.999");
        assert_eq!(lid4.device, 1);
        assert_eq!(lid4.agent, 0);
    }

    /// Test that protocol address generation from LID JIDs matches WhatsApp Web format
    ///
    /// WhatsApp Web uses: {user}[:device]@{server}.0
    /// - The device is encoded in the name
    /// - device_id is always 0
    #[test]
    fn test_lid_protocol_address_consistency() {
        use wacore::types::jid::JidExt as CoreJidExt;
        use wacore_binary::jid::Jid;

        // Format: (jid_str, expected_name, expected_device_id, expected_to_string)
        let test_cases = vec![
            (
                "100000000000001.1:75@lid",
                "100000000000001.1:75@lid",
                0,
                "100000000000001.1:75@lid.0",
            ),
            (
                "987654321000000.2:42@lid",
                "987654321000000.2:42@lid",
                0,
                "987654321000000.2:42@lid.0",
            ),
            (
                "111.222.333:10@lid",
                "111.222.333:10@lid",
                0,
                "111.222.333:10@lid.0",
            ),
            // No device - should not include :0
            ("123456789@lid", "123456789@lid", 0, "123456789@lid.0"),
        ];

        for (jid_str, expected_name, expected_device_id, expected_to_string) in test_cases {
            let lid_jid: Jid = jid_str.parse().expect("test JID should be valid");
            let protocol_addr = lid_jid.to_protocol_address();

            assert_eq!(
                protocol_addr.name(),
                expected_name,
                "Protocol address name should match WhatsApp Web's SignalAddress format for {}",
                jid_str
            );
            assert_eq!(
                u32::from(protocol_addr.device_id()),
                expected_device_id,
                "Protocol address device_id should always be 0 for {}",
                jid_str
            );
            assert_eq!(
                protocol_addr.to_string(),
                expected_to_string,
                "Protocol address to_string() should match createSignalLikeAddress format for {}",
                jid_str
            );
        }
    }

    /// Test sender_alt extraction from message attributes in LID groups
    ///
    /// Edge cases:
    /// - LID group with participant_pn attribute
    /// - PN group with participant_lid attribute
    /// - Mixed addressing modes
    #[tokio::test]
    async fn test_parse_message_info_sender_alt_extraction() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore_binary::builder::NodeBuilder;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_sender_alt_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );

        // Set up own phone number and LID
        {
            let device_arc = pm.get_device_arc().await;
            let mut device = device_arc.write().await;
            device.pn = Some(
                "15551234567@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
            );
            device.lid = Some(
                "100000000000001.1@lid"
                    .parse()
                    .expect("test JID should be valid"),
            );
        }

        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        // Test case 1: LID group message with participant_pn
        let lid_group_node = NodeBuilder::new("message")
            .attr("from", "120363021033254949@g.us")
            .attr("participant", "987654321000000.2:42@lid")
            .attr("participant_pn", "551234567890:42@s.whatsapp.net")
            .attr("addressing_mode", "lid")
            .attr("id", "test1")
            .attr("t", "12345")
            .build();

        let info1 = client
            .parse_message_info(&lid_group_node)
            .await
            .expect("parse_message_info should succeed");
        assert_eq!(info1.source.sender.user, "987654321000000.2");
        assert!(info1.source.sender_alt.is_some());
        assert_eq!(
            info1
                .source
                .sender_alt
                .as_ref()
                .expect("sender_alt should be present")
                .user,
            "551234567890"
        );

        // Test case 2: Self-sent LID group message
        let self_lid_node = NodeBuilder::new("message")
            .attr("from", "120363021033254949@g.us")
            .attr("participant", "100000000000001.1:75@lid")
            .attr("participant_pn", "15551234567:75@s.whatsapp.net")
            .attr("addressing_mode", "lid")
            .attr("id", "test2")
            .attr("t", "12346")
            .build();

        let info2 = client
            .parse_message_info(&self_lid_node)
            .await
            .expect("parse_message_info should succeed");
        assert!(
            info2.source.is_from_me,
            "Should detect self-sent LID message"
        );
        assert_eq!(info2.source.sender.user, "100000000000001.1");
        assert!(info2.source.sender_alt.is_some());
        assert_eq!(
            info2
                .source
                .sender_alt
                .as_ref()
                .expect("sender_alt should be present")
                .user,
            "15551234567"
        );
    }

    /// Test that device query logic uses phone numbers for LID participants
    ///
    /// This is a unit test for the logic in wacore/src/send.rs that converts
    /// LID JIDs to phone number JIDs for device queries.
    #[test]
    fn test_lid_to_phone_mapping_for_device_queries() {
        use std::collections::HashMap;
        use wacore::client::context::GroupInfo;
        use wacore::types::message::AddressingMode;
        use wacore_binary::jid::Jid;

        // Simulate a LID group with phone number mappings
        let mut lid_to_pn_map = HashMap::new();
        lid_to_pn_map.insert(
            "100000000000001.1".to_string(),
            "15551234567@s.whatsapp.net"
                .parse()
                .expect("test JID should be valid"),
        );
        lid_to_pn_map.insert(
            "987654321000000.2".to_string(),
            "551234567890@s.whatsapp.net"
                .parse()
                .expect("test JID should be valid"),
        );

        let mut group_info = GroupInfo::new(
            vec![
                "100000000000001.1:75@lid"
                    .parse()
                    .expect("test JID should be valid"),
                "987654321000000.2:42@lid"
                    .parse()
                    .expect("test JID should be valid"),
            ],
            AddressingMode::Lid,
        );
        group_info.set_lid_to_pn_map(lid_to_pn_map.clone());

        // Simulate the device query logic
        let jids_to_query: Vec<Jid> = group_info
            .participants
            .iter()
            .map(|jid| {
                let base_jid = jid.to_non_ad();
                if base_jid.is_lid()
                    && let Some(phone_jid) = group_info.phone_jid_for_lid_user(&base_jid.user)
                {
                    return phone_jid.to_non_ad();
                }
                base_jid
            })
            .collect();

        // Verify all queries use phone numbers, not LID JIDs
        for jid in &jids_to_query {
            assert_eq!(
                jid.server, SERVER_JID,
                "Device query should use phone number, got: {}",
                jid
            );
        }

        assert_eq!(jids_to_query.len(), 2);
        assert!(jids_to_query.iter().any(|j| j.user == "15551234567"));
        assert!(jids_to_query.iter().any(|j| j.user == "551234567890"));
    }

    /// Test edge case: Group with mixed LID and phone number participants
    ///
    /// Some participants may still use phone numbers even in a LID group.
    /// The code should handle both correctly.
    #[test]
    fn test_mixed_lid_and_phone_participants() {
        use std::collections::HashMap;
        use wacore::client::context::GroupInfo;
        use wacore::types::message::AddressingMode;
        use wacore_binary::jid::Jid;

        let mut lid_to_pn_map = HashMap::new();
        lid_to_pn_map.insert(
            "100000000000001.1".to_string(),
            "15551234567@s.whatsapp.net"
                .parse()
                .expect("test JID should be valid"),
        );

        let mut group_info = GroupInfo::new(
            vec![
                "100000000000001.1:75@lid"
                    .parse()
                    .expect("test JID should be valid"), // LID participant
                "551234567890:42@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"), // Phone number participant
            ],
            AddressingMode::Lid,
        );
        group_info.set_lid_to_pn_map(lid_to_pn_map.clone());

        let jids_to_query: Vec<Jid> = group_info
            .participants
            .iter()
            .map(|jid| {
                let base_jid = jid.to_non_ad();
                if base_jid.is_lid()
                    && let Some(phone_jid) = group_info.phone_jid_for_lid_user(&base_jid.user)
                {
                    return phone_jid.to_non_ad();
                }
                base_jid
            })
            .collect();

        // Both should end up as phone numbers
        assert_eq!(jids_to_query.len(), 2);
        for jid in &jids_to_query {
            assert_eq!(jid.server, SERVER_JID);
        }
    }

    /// Test edge case: Own JID check in LID mode
    ///
    /// When checking if own JID is in the participant list, we must use
    /// the phone number equivalent if in LID mode, not the LID itself.
    #[test]
    fn test_own_jid_check_in_lid_mode() {
        use std::collections::HashMap;
        use wacore_binary::jid::Jid;

        let own_lid: Jid = "100000000000001.1@lid"
            .parse()
            .expect("test JID should be valid");
        let own_phone: Jid = "15551234567@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        let mut lid_to_pn_map = HashMap::new();
        lid_to_pn_map.insert("100000000000001.1".to_string(), own_phone.clone());

        // Simulate the own JID check logic from wacore/src/send.rs
        let own_base_jid = own_lid.to_non_ad();
        let own_jid_to_check = if own_base_jid.is_lid() {
            lid_to_pn_map
                .get(&own_base_jid.user)
                .map(|pn| pn.to_non_ad())
                .unwrap_or_else(|| own_base_jid.clone())
        } else {
            own_base_jid.clone()
        };

        // Verify we're checking using the phone number
        assert_eq!(own_jid_to_check.user, "15551234567");
        assert_eq!(own_jid_to_check.server, SERVER_JID);
    }

    /// Test that sender key operations always use the display JID (LID)
    /// regardless of what JID is used for E2E session decryption
    #[tokio::test]
    async fn test_sender_key_always_uses_display_jid() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::libsignal::protocol::{SenderKeyStore, create_sender_key_distribution_message};
        use wacore::libsignal::store::sender_key_name::SenderKeyName;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_display_jid_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (_client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");
        let display_jid: Jid = "100000000000001.1:75@lid"
            .parse()
            .expect("test JID should be valid");
        let encryption_jid: Jid = "15551234567:75@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        // Store sender key using display JID (LID)
        let display_protocol_address = display_jid.to_protocol_address();
        let display_sender_key_name =
            SenderKeyName::new(group_jid.to_string(), display_protocol_address.to_string());

        let device_arc = pm.get_device_arc().await;
        {
            let mut device_guard = device_arc.write().await;
            create_sender_key_distribution_message(
                &display_sender_key_name,
                &mut *device_guard,
                &mut rand::make_rng::<rand::rngs::StdRng>(),
            )
            .await
            .expect("Failed to create SKDM");
        }

        // Verify it's stored under display JID
        let lookup_with_display = {
            let mut device_guard = device_arc.write().await;
            device_guard.load_sender_key(&display_sender_key_name).await
        };
        assert!(
            lookup_with_display
                .expect("lookup should not error")
                .is_some(),
            "Sender key should be found with display JID (LID)"
        );

        // Verify it's NOT accessible via encryption JID (phone number)
        let encryption_protocol_address = encryption_jid.to_protocol_address();
        let encryption_sender_key_name = SenderKeyName::new(
            group_jid.to_string(),
            encryption_protocol_address.to_string(),
        );

        let lookup_with_encryption = {
            let mut device_guard = device_arc.write().await;
            device_guard
                .load_sender_key(&encryption_sender_key_name)
                .await
        };
        assert!(
            lookup_with_encryption
                .expect("lookup should not error")
                .is_none(),
            "Sender key should NOT be found with encryption JID (phone number)"
        );
    }

    /// Test edge case: Second message with only skmsg (no pkmsg/msg)
    ///
    /// After the first message establishes a session and sender key,
    /// subsequent messages may contain only skmsg. These should still
    /// be decrypted successfully, not skipped.
    ///
    /// Bug: The code was treating "no session messages" as "session failed",
    /// causing it to skip skmsg decryption for all messages after the first.
    #[tokio::test]
    async fn test_second_message_with_only_skmsg_decrypts() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::libsignal::protocol::{
            create_sender_key_distribution_message, process_sender_key_distribution_message,
        };
        use wacore::libsignal::store::sender_key_name::SenderKeyName;
        use wacore_binary::builder::NodeBuilder;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_second_msg_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let sender_jid: Jid = "100000000000001.1:75@lid"
            .parse()
            .expect("test JID should be valid");
        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");

        // Step 1: Create and store a sender key (simulating first message processing)
        let sender_protocol_address = sender_jid.to_protocol_address();
        let sender_key_name =
            SenderKeyName::new(group_jid.to_string(), sender_protocol_address.to_string());

        let device_arc = pm.get_device_arc().await;
        {
            let mut device_guard = device_arc.write().await;
            let skdm = create_sender_key_distribution_message(
                &sender_key_name,
                &mut *device_guard,
                &mut rand::make_rng::<rand::rngs::StdRng>(),
            )
            .await
            .expect("Failed to create SKDM");

            process_sender_key_distribution_message(&sender_key_name, &skdm, &mut *device_guard)
                .await
                .expect("Failed to process SKDM");
        }

        // Create message with ONLY skmsg (simulating second message after session established)
        let skmsg_ciphertext = {
            let mut device_guard = device_arc.write().await;
            let sender_key_msg = wacore::libsignal::protocol::group_encrypt(
                &mut *device_guard,
                &sender_key_name,
                b"ping",
                &mut rand::make_rng::<rand::rngs::StdRng>(),
            )
            .await
            .expect("Failed to encrypt with sender key");
            sender_key_msg.serialized().to_vec()
        };

        let skmsg_node = NodeBuilder::new("enc")
            .attr("type", "skmsg")
            .attr("v", "2")
            .bytes(skmsg_ciphertext)
            .build();

        let message_node = Arc::new(
            NodeBuilder::new("message")
                .attr("from", group_jid)
                .attr("participant", sender_jid)
                .attr("id", "SECOND_MSG_TEST")
                .attr("t", "1759306493")
                .attr("type", "text")
                .attr("addressing_mode", "lid")
                .children(vec![skmsg_node])
                .build(),
        );

        // Should NOT skip skmsg - before the fix this would incorrectly skip
        client.handle_incoming_message(message_node).await;
    }

    /// Test case for UntrustedIdentity error handling and recovery
    ///
    /// Scenario:
    /// - User re-installs WhatsApp or switches devices
    /// - Their device generates a new identity key
    /// - The bot still has the old identity key stored
    /// - When a message arrives, Signal Protocol rejects it as "UntrustedIdentity"
    /// - The bot should catch this error, clear the old identity using the FULL protocol address (with device ID), and retry
    ///
    /// This test verifies that:
    /// 1. process_session_enc_batch handles UntrustedIdentity gracefully
    /// 2. The deletion uses the correct full address (name.device_id) not just the name
    /// 3. No panic occurs when UntrustedIdentity is encountered
    /// 4. The error is logged appropriately
    /// 5. The bot continues processing instead of propagating the error
    #[tokio::test]
    async fn test_untrusted_identity_error_is_caught_and_handled() {
        use crate::store::SqliteStore;
        use std::sync::Arc;

        // Setup
        let backend = Arc::new(
            SqliteStore::new("file:memdb_untrusted_identity_caught?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let sender_jid: Jid = "559981212574@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        let info = MessageInfo {
            source: crate::types::message::MessageSource {
                sender: sender_jid.clone(),
                chat: sender_jid.clone(),
                ..Default::default()
            },
            ..Default::default()
        };

        log::info!("Test: UntrustedIdentity scenario for {}", sender_jid);

        // Create a malformed/invalid encrypted node to trigger error handling path
        // This won't create UntrustedIdentity specifically, but tests the error handling code path
        // The important fix is that when UntrustedIdentity IS raised, the code uses
        // address.to_string() (which gives "559981212574.0") instead of address.name()
        // (which only gives "559981212574") for the deletion key.
        let enc_node = NodeBuilder::new("enc")
            .attr("type", "msg")
            .attr("v", "2")
            .bytes(vec![0xFF; 100]) // Invalid encrypted payload
            .build();

        let enc_nodes = vec![&enc_node];

        // Call process_session_enc_batch
        // This should handle any errors gracefully without panicking
        let (success, _had_duplicates, _dispatched) = client
            .process_session_enc_batch(
                &enc_nodes,
                &info,
                &sender_jid,
                crate::types::events::DecryptFailMode::Show,
            )
            .await;

        log::info!(
            "Test: process_session_enc_batch completed - success: {}",
            success
        );

        // The key is that this didn't panic - deletion uses full protocol address
    }

    /// Test case: Error handling during batch processing
    ///
    /// When multiple messages are being processed in a batch, if one triggers
    /// an error (like UntrustedIdentity), it should be handled without affecting
    /// other messages in the batch.
    #[tokio::test]
    async fn test_untrusted_identity_does_not_break_batch_processing() {
        use crate::store::SqliteStore;
        use std::sync::Arc;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_untrusted_batch?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let sender_jid: Jid = "559981212574@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        let info = MessageInfo {
            source: crate::types::message::MessageSource {
                sender: sender_jid.clone(),
                chat: sender_jid.clone(),
                ..Default::default()
            },
            ..Default::default()
        };

        log::info!("Test: Batch processing with multiple error messages");

        // Create multiple invalid encrypted nodes to test batch error handling
        let mut enc_nodes = Vec::new();

        // First message: Invalid encrypted payload
        let enc_node_1 = NodeBuilder::new("enc")
            .attr("type", "msg")
            .attr("v", "2")
            .bytes(vec![0xFF; 50])
            .build();
        enc_nodes.push(enc_node_1);

        // Second message: Another invalid encrypted payload
        let enc_node_2 = NodeBuilder::new("enc")
            .attr("type", "msg")
            .attr("v", "2")
            .bytes(vec![0xAA; 50])
            .build();
        enc_nodes.push(enc_node_2);

        log::info!("Test: Created batch of 2 messages with invalid data");

        let enc_node_refs: Vec<&wacore_binary::node::Node> = enc_nodes.iter().collect();

        // Process the batch
        // Should handle all errors gracefully without stopping at first error
        let (success, _had_duplicates, _dispatched) = client
            .process_session_enc_batch(
                &enc_node_refs,
                &info,
                &sender_jid,
                crate::types::events::DecryptFailMode::Show,
            )
            .await;

        log::info!("Test: Batch processing completed - success: {}", success);
    }

    /// Test case: Error handling in group chat context
    ///
    /// When processing messages from group members, if identity errors occur,
    /// they should be handled per-sender without affecting other group members.
    #[tokio::test]
    async fn test_untrusted_identity_in_group_context() {
        use crate::store::SqliteStore;
        use std::sync::Arc;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_untrusted_group?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        // Simulate a group chat scenario
        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");
        let sender_phone: Jid = "559981212574@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        let info = MessageInfo {
            source: crate::types::message::MessageSource {
                sender: sender_phone.clone(),
                chat: group_jid.clone(),
                is_group: true,
                ..Default::default()
            },
            ..Default::default()
        };

        log::info!("Test: Group context - error handling for {}", sender_phone);

        // Create an invalid encrypted message
        let enc_node = NodeBuilder::new("enc")
            .attr("type", "msg")
            .attr("v", "2")
            .bytes(vec![0xFF; 100])
            .build();

        let enc_nodes = vec![&enc_node];

        // Process the message
        // Should handle errors gracefully in group context
        let (success, _had_duplicates, _dispatched) = client
            .process_session_enc_batch(
                &enc_nodes,
                &info,
                &sender_phone,
                crate::types::events::DecryptFailMode::Show,
            )
            .await;

        log::info!("Test: Group message processed - success: {}", success);
    }

    /// Test case: DM message parsing for self-sent messages via LID
    ///
    /// Scenario:
    /// - You send a DM to another user from your phone
    /// - Your bot receives the echo with from=your_LID, recipient=their_LID
    /// - peer_recipient_pn contains the RECIPIENT's phone number (not sender's)
    ///
    /// The fix ensures:
    /// 1. is_from_me is correctly detected for LID senders
    /// 2. sender_alt is NOT populated with peer_recipient_pn (that's the recipient's PN)
    /// 3. Decryption uses own PN via the is_from_me fallback path
    #[tokio::test]
    async fn test_parse_message_info_self_sent_dm_via_lid() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore_binary::builder::NodeBuilder;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_self_dm_lid_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );

        // Set up own phone number and LID
        {
            let device_arc = pm.get_device_arc().await;
            let mut device = device_arc.write().await;
            device.pn = Some(
                "15551234567@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
            );
            device.lid = Some(
                "100000000000001@lid"
                    .parse()
                    .expect("test JID should be valid"),
            );
        }

        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        // Simulate self-sent DM to another user (from your phone to your bot echo)
        // Real log example:
        // from="100000000000001@lid" recipient="39492358562039@lid" peer_recipient_pn="559985213786@s.whatsapp.net"
        let self_dm_node = NodeBuilder::new("message")
            .attr("from", "100000000000001@lid") // Your LID
            .attr("recipient", "39492358562039@lid") // Recipient's LID
            .attr("peer_recipient_pn", "559985213786@s.whatsapp.net") // Recipient's PN (NOT sender's!)
            .attr("notify", "jl")
            .attr("id", "AC756E00B560721DBC4C0680131827EA")
            .attr("t", "1764845025")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&self_dm_node)
            .await
            .expect("parse_message_info should succeed");

        // Assertions:
        // 1. is_from_me should be true (LID matches own_lid)
        assert!(
            info.source.is_from_me,
            "Should detect self-sent DM from own LID"
        );

        // 2. sender_alt should be None (peer_recipient_pn is recipient's PN, not sender's)
        assert!(
            info.source.sender_alt.is_none(),
            "sender_alt should be None for self-sent DMs (peer_recipient_pn is recipient's PN)"
        );

        assert_eq!(
            info.source.chat.user, "39492358562039",
            "Chat should be the recipient's LID"
        );

        assert_eq!(
            info.source.sender.user, "100000000000001",
            "Sender should be own LID"
        );
    }

    /// Test case: DM message parsing for messages from others via LID
    ///
    /// Scenario:
    /// - Another user sends you a DM
    /// - Message arrives with from=their_LID, sender_pn=their_phone_number
    ///
    /// The fix ensures:
    /// 1. is_from_me is false
    /// 2. sender_alt is populated from sender_pn attribute (if present)
    /// 3. Decryption uses sender_alt for session lookup
    #[tokio::test]
    async fn test_parse_message_info_dm_from_other_via_lid() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore_binary::builder::NodeBuilder;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_other_dm_lid_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );

        // Set up own phone number and LID
        {
            let device_arc = pm.get_device_arc().await;
            let mut device = device_arc.write().await;
            device.pn = Some(
                "15551234567@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
            );
            device.lid = Some(
                "100000000000001@lid"
                    .parse()
                    .expect("test JID should be valid"),
            );
        }

        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        // Simulate DM from another user via their LID
        // The sender_pn attribute should contain their phone number for session lookup
        let other_dm_node = NodeBuilder::new("message")
            .attr("from", "39492358562039@lid") // Sender's LID (not ours)
            .attr("sender_pn", "559985213786@s.whatsapp.net") // Sender's phone number
            .attr("notify", "Other User")
            .attr("id", "AABBCCDD1234567890")
            .attr("t", "1764845100")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&other_dm_node)
            .await
            .expect("parse_message_info should succeed");

        assert!(
            !info.source.is_from_me,
            "Should NOT be detected as self-sent"
        );

        assert!(
            info.source.sender_alt.is_some(),
            "sender_alt should be set from sender_pn attribute"
        );
        assert_eq!(
            info.source
                .sender_alt
                .as_ref()
                .expect("sender_alt should be present")
                .user,
            "559985213786",
            "sender_alt should contain sender's phone number"
        );

        assert_eq!(
            info.source.chat.user, "39492358562039",
            "Chat should be the sender's LID (non-AD)"
        );

        assert_eq!(
            info.source.sender.user, "39492358562039",
            "Sender should be other user's LID"
        );
    }

    /// Test case: DM message to self (own chat, like "Notes to Myself")
    ///
    /// Scenario:
    /// - You send a message to yourself (your own chat)
    /// - from=your_LID, recipient=your_LID, peer_recipient_pn=your_PN
    ///
    /// This is the original bug case that was fixed earlier.
    #[tokio::test]
    async fn test_parse_message_info_dm_to_self() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore_binary::builder::NodeBuilder;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_dm_to_self_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );

        // Set up own phone number and LID
        {
            let device_arc = pm.get_device_arc().await;
            let mut device = device_arc.write().await;
            device.pn = Some(
                "15551234567@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
            );
            device.lid = Some(
                "100000000000001@lid"
                    .parse()
                    .expect("test JID should be valid"),
            );
        }

        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        // Simulate DM to self (like "Notes to Myself" or pinging yourself)
        // from=your_LID, recipient=your_LID, peer_recipient_pn=your_PN
        let self_chat_node = NodeBuilder::new("message")
            .attr("from", "100000000000001@lid") // Your LID
            .attr("recipient", "100000000000001@lid") // Also your LID (self-chat)
            .attr("peer_recipient_pn", "15551234567@s.whatsapp.net") // Your PN
            .attr("notify", "jl")
            .attr("id", "AC391DD54A28E1CE1F3B106DF9951FAD")
            .attr("t", "1764822437")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&self_chat_node)
            .await
            .expect("parse_message_info should succeed");

        assert!(
            info.source.is_from_me,
            "Should detect self-sent message to self-chat"
        );

        assert!(
            info.source.sender_alt.is_none(),
            "sender_alt should be None for self-sent messages"
        );

        assert_eq!(
            info.source.chat.user, "100000000000001",
            "Chat should be self (recipient)"
        );

        assert_eq!(
            info.source.sender.user, "100000000000001",
            "Sender should be own LID"
        );
    }

    /// Test that receiving a DM with sender_lid populates the lid_pn_cache.
    ///
    /// This is the key behavior for the LID-PN session mismatch fix:
    /// When we receive a message from a phone number with sender_lid attribute,
    /// 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.
    ///
    /// Flow being tested:
    /// 1. Receive message from 559980000001@s.whatsapp.net with sender_lid=100000012345678@lid
    /// 2. Cache should be populated with: 559980000001 -> 100000012345678
    /// 3. When sending reply to 559980000001, we can look up the LID and use existing session
    #[tokio::test]
    async fn test_lid_pn_cache_populated_on_message_with_sender_lid() {
        // Setup client
        let backend = Arc::new(
            SqliteStore::new("file:memdb_lid_cache_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

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

        // Verify cache is empty initially
        assert!(
            client.lid_pn_cache.get_current_lid(phone).await.is_none(),
            "Cache should be empty before receiving message"
        );

        // Create a DM message node with sender_lid attribute
        // This simulates receiving a message from WhatsApp Web
        let dm_node = NodeBuilder::new("message")
            .attr("from", Jid::pn(phone).to_string())
            .attr("sender_lid", Jid::lid(lid).to_string())
            .attr("id", "TEST123456789")
            .attr("t", "1765482972")
            .attr("type", "text")
            .children([NodeBuilder::new("enc")
                .attr("type", "pkmsg")
                .attr("v", "2")
                .bytes(vec![0u8; 100]) // Dummy encrypted content
                .build()])
            .build();

        // Call handle_incoming_message - this will fail to decrypt (no real session)
        // but it should still populate the cache before attempting decryption
        client
            .clone()
            .handle_incoming_message(Arc::new(dm_node))
            .await;

        // Verify the cache was populated
        let cached_lid = client.lid_pn_cache.get_current_lid(phone).await;
        assert!(
            cached_lid.is_some(),
            "Cache should be populated after receiving message with sender_lid"
        );
        assert_eq!(
            cached_lid.expect("cache should have LID"),
            lid,
            "Cached LID should match the sender_lid from the message"
        );
    }

    /// Test that messages without sender_lid do NOT populate the cache.
    ///
    /// This ensures we don't accidentally cache incorrect mappings.
    #[tokio::test]
    async fn test_lid_pn_cache_not_populated_without_sender_lid() {
        // Setup client
        let backend = Arc::new(
            SqliteStore::new("file:memdb_no_lid_cache_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let phone = "559980000001";

        // Create a DM message node WITHOUT sender_lid attribute
        let dm_node = NodeBuilder::new("message")
            .attr("from", Jid::pn(phone).to_string())
            // Note: NO sender_lid attribute
            .attr("id", "TEST123456789")
            .attr("t", "1765482972")
            .attr("type", "text")
            .children([NodeBuilder::new("enc")
                .attr("type", "pkmsg")
                .attr("v", "2")
                .bytes(vec![0u8; 100])
                .build()])
            .build();

        // Call handle_incoming_message
        client
            .clone()
            .handle_incoming_message(Arc::new(dm_node))
            .await;

        assert!(
            client.lid_pn_cache.get_current_lid(phone).await.is_none(),
            "Cache should NOT be populated for messages without sender_lid"
        );
    }

    /// Test that messages from LID senders with participant_pn DO populate the cache.
    ///
    /// When the sender is a LID (e.g., in LID-mode groups), and participant_pn
    /// contains their phone number, we SHOULD cache this mapping because:
    /// 1. The cache is bidirectional - we need both LID->PN and PN->LID
    /// 2. This enables sending to users we've only seen as LID senders
    #[tokio::test]
    async fn test_lid_pn_cache_populated_for_lid_sender_with_participant_pn() {
        // Setup client
        let backend = Arc::new(
            SqliteStore::new("file:memdb_lid_sender_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

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

        // Create a message from a LID sender with participant_pn attribute
        // This happens in LID-mode groups (addressing_mode="lid")
        let group_node = NodeBuilder::new("message")
            .attr("from", "120363123456789012@g.us") // Group chat
            .attr("participant", Jid::lid(lid).to_string()) // Sender is LID
            .attr("participant_pn", Jid::pn(phone).to_string()) // Their phone number
            .attr("addressing_mode", "lid") // Required for participant_pn to be parsed
            .attr("id", "TEST123456789")
            .attr("t", "1765482972")
            .attr("type", "text")
            .children([NodeBuilder::new("enc")
                .attr("type", "skmsg")
                .attr("v", "2")
                .bytes(vec![0u8; 100])
                .build()])
            .build();

        // Call handle_incoming_message
        client
            .clone()
            .handle_incoming_message(Arc::new(group_node))
            .await;

        // Verify the cache WAS populated (bidirectional cache)
        let cached_lid = client.lid_pn_cache.get_current_lid(phone).await;
        assert!(
            cached_lid.is_some(),
            "Cache should be populated for LID senders with participant_pn"
        );
        assert_eq!(
            cached_lid.expect("cache should have LID"),
            lid,
            "Cached LID should match the sender's LID"
        );

        // Also verify we can look up the phone number from the LID
        let cached_pn = client.lid_pn_cache.get_phone_number(lid).await;
        assert!(cached_pn.is_some(), "Reverse lookup (LID->PN) should work");
        assert_eq!(
            cached_pn.expect("reverse lookup should return phone"),
            phone,
            "Cached phone number should match"
        );
    }

    /// Test that multiple messages from the same sender update the cache correctly.
    ///
    /// This ensures the cache handles repeated messages gracefully.
    #[tokio::test]
    async fn test_lid_pn_cache_handles_repeated_messages() {
        // Setup client
        let backend = Arc::new(
            SqliteStore::new("file:memdb_repeated_msg_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

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

        // Send multiple messages from the same sender
        for i in 0..3 {
            let dm_node = NodeBuilder::new("message")
                .attr("from", Jid::pn(phone).to_string())
                .attr("sender_lid", Jid::lid(lid).to_string())
                .attr("id", format!("TEST{}", i))
                .attr("t", "1765482972")
                .attr("type", "text")
                .children([NodeBuilder::new("enc")
                    .attr("type", "pkmsg")
                    .attr("v", "2")
                    .bytes(vec![0u8; 100])
                    .build()])
                .build();

            client
                .clone()
                .handle_incoming_message(Arc::new(dm_node))
                .await;
        }

        // Verify the cache still has the correct mapping
        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 be correct after multiple messages"
        );
    }

    /// Test that PN-addressed messages use LID for session lookup when LID mapping is known.
    ///
    /// This test verifies the fix for the MAC verification failure bug:
    /// WhatsApp Web's SignalAddress.toString() ALWAYS converts PN addresses to LID
    /// when a LID mapping is known. The Rust client must do the same to ensure
    /// session keys match between clients.
    ///
    /// Bug scenario:
    /// 1. WhatsApp Web Client A sends a group message to our Rust client
    /// 2. Rust client creates session under PN address (559980000001@c.us.0)
    /// 3. Rust client sends group response, creates session under LID (100000012345678@lid.0)
    /// 4. Client A sends DM to Rust client from PN address
    /// 5. Rust client tries to decrypt using PN address but session is under LID
    /// 6. MAC verification fails because wrong session is used
    ///
    /// Fix: When receiving a PN-addressed message, if we have a LID mapping,
    /// use the LID address for session lookup (matching WhatsApp Web behavior).
    #[tokio::test]
    async fn test_pn_message_uses_lid_for_session_lookup_when_mapping_known() {
        use crate::lid_pn_cache::LidPnEntry;
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::types::jid::JidExt;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_pn_to_lid_session_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

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

        // Pre-populate the LID-PN cache (simulating a previous group message)
        let entry = LidPnEntry::new(
            lid.to_string(),
            phone.to_string(),
            crate::lid_pn_cache::LearningSource::PeerLidMessage,
        );
        client.lid_pn_cache.add(entry).await;

        // Verify the cache has the mapping
        let cached_lid = client.lid_pn_cache.get_current_lid(phone).await;
        assert_eq!(
            cached_lid,
            Some(lid.to_string()),
            "Cache should have the LID-PN mapping"
        );

        // Test scenario: Parse a PN-addressed DM message (with sender_lid attribute)
        let dm_node_with_sender_lid = wacore_binary::builder::NodeBuilder::new("message")
            .attr("from", Jid::pn(phone).to_string())
            .attr("sender_lid", Jid::lid(lid).to_string())
            .attr("id", "test_dm_with_lid")
            .attr("t", "1765494882")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&dm_node_with_sender_lid)
            .await
            .expect("parse_message_info should succeed");

        // Verify sender is PN but sender_alt is LID
        assert_eq!(info.source.sender.user, phone);
        assert_eq!(info.source.sender.server, "s.whatsapp.net");
        assert!(info.source.sender_alt.is_some());
        assert_eq!(
            info.source
                .sender_alt
                .as_ref()
                .expect("sender_alt should be present")
                .user,
            lid
        );
        assert_eq!(
            info.source
                .sender_alt
                .as_ref()
                .expect("sender_alt should be present")
                .server,
            "lid"
        );

        // Now simulate what handle_incoming_message does: determine encryption JID
        // We can't easily call handle_incoming_message, so we'll test the logic directly
        let sender = &info.source.sender;
        let alt = info.source.sender_alt.as_ref();
        let pn_server = wacore_binary::jid::DEFAULT_USER_SERVER;
        let lid_server = wacore_binary::jid::HIDDEN_USER_SERVER;

        // Apply the same logic as in handle_incoming_message
        let sender_encryption_jid = if sender.server == lid_server {
            sender.clone()
        } else if sender.server == pn_server {
            if let Some(alt_jid) = alt
                && alt_jid.server == lid_server
            {
                // Use the LID from the message attribute
                Jid {
                    user: alt_jid.user.clone(),
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else if let Some(lid_user) = client.lid_pn_cache.get_current_lid(&sender.user).await {
                // Use the cached LID
                Jid {
                    user: lid_user,
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else {
                sender.clone()
            }
        } else {
            sender.clone()
        };

        // Verify the encryption JID uses the LID, not the PN
        assert_eq!(
            sender_encryption_jid.user, lid,
            "Encryption JID should use LID user"
        );
        assert_eq!(
            sender_encryption_jid.server, "lid",
            "Encryption JID should use LID server"
        );

        // Verify the protocol address format
        let protocol_address = sender_encryption_jid.to_protocol_address();
        assert_eq!(
            protocol_address.to_string(),
            format!("{}@lid.0", lid),
            "Protocol address should be in LID format"
        );
    }

    /// Test that PN-addressed messages use cached LID even without sender_lid attribute.
    ///
    /// This tests the fallback path where the message doesn't have a sender_lid
    /// attribute but we have a previously cached LID mapping.
    #[tokio::test]
    async fn test_pn_message_uses_cached_lid_without_sender_lid_attribute() {
        use crate::lid_pn_cache::LidPnEntry;
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::types::jid::JidExt;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_cached_lid_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

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

        // Pre-populate the LID-PN cache
        let entry = LidPnEntry::new(
            lid.to_string(),
            phone.to_string(),
            crate::lid_pn_cache::LearningSource::PeerLidMessage,
        );
        client.lid_pn_cache.add(entry).await;

        // Parse a PN-addressed DM message WITHOUT sender_lid attribute
        let dm_node_without_sender_lid = wacore_binary::builder::NodeBuilder::new("message")
            .attr("from", Jid::pn(phone).to_string())
            // Note: No sender_lid attribute!
            .attr("id", "test_dm_no_lid")
            .attr("t", "1765494882")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&dm_node_without_sender_lid)
            .await
            .expect("parse_message_info should succeed");

        // Verify sender is PN and NO sender_alt (since there's no sender_lid attribute)
        assert_eq!(info.source.sender.user, phone);
        assert_eq!(info.source.sender.server, "s.whatsapp.net");
        assert!(
            info.source.sender_alt.is_none(),
            "Should have no sender_alt without sender_lid attribute"
        );

        // Apply the encryption JID logic (fallback to cached LID)
        let sender = &info.source.sender;
        let alt = info.source.sender_alt.as_ref();
        let pn_server = wacore_binary::jid::DEFAULT_USER_SERVER;
        let lid_server = wacore_binary::jid::HIDDEN_USER_SERVER;

        let sender_encryption_jid = if sender.server == lid_server {
            sender.clone()
        } else if sender.server == pn_server {
            if let Some(alt_jid) = alt
                && alt_jid.server == lid_server
            {
                Jid {
                    user: alt_jid.user.clone(),
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else if let Some(lid_user) = client.lid_pn_cache.get_current_lid(&sender.user).await {
                // This is the path we're testing - fallback to cached LID
                Jid {
                    user: lid_user,
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else {
                sender.clone()
            }
        } else {
            sender.clone()
        };

        // Verify the encryption JID uses the cached LID
        assert_eq!(
            sender_encryption_jid.user, lid,
            "Encryption JID should use cached LID user"
        );
        assert_eq!(
            sender_encryption_jid.server, "lid",
            "Encryption JID should use LID server"
        );

        let protocol_address = sender_encryption_jid.to_protocol_address();
        assert_eq!(
            protocol_address.to_string(),
            format!("{}@lid.0", lid),
            "Protocol address should be in LID format from cached mapping"
        );
    }

    /// Test that PN-addressed messages use PN when no LID mapping is known.
    ///
    /// When there's no LID mapping available, we should fall back to using
    /// the PN address for session lookup.
    #[tokio::test]
    async fn test_pn_message_uses_pn_when_no_lid_mapping() {
        use crate::store::SqliteStore;
        use std::sync::Arc;
        use wacore::types::jid::JidExt;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_no_lid_mapping_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let phone = "559980000001";

        // Don't populate the cache - simulate first-time contact

        // Parse a PN-addressed DM message without sender_lid
        let dm_node = wacore_binary::builder::NodeBuilder::new("message")
            .attr("from", Jid::pn(phone).to_string())
            .attr("id", "test_dm_no_mapping")
            .attr("t", "1765494882")
            .attr("type", "text")
            .build();

        let info = client
            .parse_message_info(&dm_node)
            .await
            .expect("parse_message_info should succeed");

        // Verify no cached LID
        let cached_lid = client.lid_pn_cache.get_current_lid(phone).await;
        assert!(cached_lid.is_none(), "Should have no cached LID mapping");

        // Apply the encryption JID logic
        let sender = &info.source.sender;
        let alt = info.source.sender_alt.as_ref();
        let pn_server = wacore_binary::jid::DEFAULT_USER_SERVER;
        let lid_server = wacore_binary::jid::HIDDEN_USER_SERVER;

        let sender_encryption_jid = if sender.server == lid_server {
            sender.clone()
        } else if sender.server == pn_server {
            if let Some(alt_jid) = alt
                && alt_jid.server == lid_server
            {
                Jid {
                    user: alt_jid.user.clone(),
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else if let Some(lid_user) = client.lid_pn_cache.get_current_lid(&sender.user).await {
                Jid {
                    user: lid_user,
                    server: wacore_binary::jid::cow_server_from_str(lid_server),
                    device: sender.device,
                    agent: sender.agent,
                    integrator: sender.integrator,
                }
            } else {
                // This is the path we're testing - no LID mapping, use PN
                sender.clone()
            }
        } else {
            sender.clone()
        };

        // Verify the encryption JID uses the PN (no LID available)
        assert_eq!(
            sender_encryption_jid.user, phone,
            "Encryption JID should use PN user when no LID mapping"
        );
        assert_eq!(
            sender_encryption_jid.server, "s.whatsapp.net",
            "Encryption JID should use PN server when no LID mapping"
        );

        let protocol_address = sender_encryption_jid.to_protocol_address();
        assert_eq!(
            protocol_address.to_string(),
            format!("{}@c.us.0", phone),
            "Protocol address should be in PN format when no LID mapping"
        );
    }

    // and PDO fallback behavior to ensure robust message recovery.

    /// Helper to create a test MessageInfo with customizable fields
    fn create_test_message_info(chat: &str, msg_id: &str, sender: &str) -> MessageInfo {
        use wacore::types::message::{EditAttribute, MessageSource, MsgMetaInfo};

        let chat_jid: Jid = chat.parse().expect("valid chat JID");
        let sender_jid: Jid = sender.parse().expect("valid sender JID");

        MessageInfo {
            id: msg_id.to_string(),
            server_id: 0,
            r#type: "text".to_string(),
            source: MessageSource {
                chat: chat_jid.clone(),
                sender: sender_jid,
                sender_alt: None,
                recipient_alt: None,
                is_from_me: false,
                is_group: chat_jid.is_group(),
                addressing_mode: None,
                broadcast_list_owner: None,
                recipient: None,
            },
            timestamp: wacore::time::now_utc(),
            push_name: "Test User".to_string(),
            category: "".to_string(),
            multicast: false,
            media_type: "".to_string(),
            edit: EditAttribute::default(),
            bot_info: None,
            meta_info: MsgMetaInfo::default(),
            verified_name: None,
            device_sent_meta: None,
        }
    }

    /// Helper to create a test client for retry tests with a unique database
    async fn create_test_client_for_retry_with_id(test_id: &str) -> Arc<Client> {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let unique_id = COUNTER.fetch_add(1, Ordering::SeqCst);
        let db_name = format!(
            "file:memdb_retry_{}_{}_{}?mode=memory&cache=shared",
            test_id,
            unique_id,
            std::process::id()
        );

        let backend = Arc::new(
            SqliteStore::new(&db_name)
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;
        client
    }

    #[tokio::test]
    async fn test_increment_retry_count_starts_at_one() {
        let client = create_test_client_for_retry_with_id("starts_at_one").await;

        let cache_key = "test_chat:msg123:sender456";

        // First increment should return 1
        let count = client.increment_retry_count(cache_key).await;
        assert_eq!(count, Some(1), "First retry should be count 1");

        // Verify it's stored in cache
        let stored = client.message_retry_counts.get(cache_key).await;
        assert_eq!(stored, Some(1), "Cache should store count 1");
    }

    #[tokio::test]
    async fn test_increment_retry_count_increments_correctly() {
        let client = create_test_client_for_retry_with_id("increments").await;

        let cache_key = "test_chat:msg456:sender789";

        // Simulate multiple retries
        let count1 = client.increment_retry_count(cache_key).await;
        let count2 = client.increment_retry_count(cache_key).await;
        let count3 = client.increment_retry_count(cache_key).await;

        assert_eq!(count1, Some(1), "First retry should be 1");
        assert_eq!(count2, Some(2), "Second retry should be 2");
        assert_eq!(count3, Some(3), "Third retry should be 3");
    }

    #[tokio::test]
    async fn test_increment_retry_count_respects_max_retries() {
        let client = create_test_client_for_retry_with_id("max_retries").await;

        let cache_key = "test_chat:msg_max:sender_max";

        // Exhaust all retries (MAX_DECRYPT_RETRIES = 5)
        for i in 1..=5 {
            let count = client.increment_retry_count(cache_key).await;
            assert_eq!(count, Some(i), "Retry {} should return {}", i, i);
        }

        // 6th attempt should return None (max reached)
        let count_after_max = client.increment_retry_count(cache_key).await;
        assert_eq!(
            count_after_max, None,
            "After max retries, should return None"
        );

        // Verify cache still has max value
        let stored = client.message_retry_counts.get(cache_key).await;
        assert_eq!(stored, Some(5), "Cache should retain max count");
    }

    #[tokio::test]
    async fn test_retry_count_different_messages_are_independent() {
        let client = create_test_client_for_retry_with_id("independent").await;

        let key1 = "chat1:msg1:sender1";
        let key2 = "chat1:msg2:sender1"; // Same chat and sender, different message
        let key3 = "chat2:msg1:sender2"; // Different chat and sender

        // Increment each independently
        let _ = client.increment_retry_count(key1).await;
        let _ = client.increment_retry_count(key1).await;
        let _ = client.increment_retry_count(key1).await; // key1 = 3

        let _ = client.increment_retry_count(key2).await; // key2 = 1

        let _ = client.increment_retry_count(key3).await;
        let _ = client.increment_retry_count(key3).await; // key3 = 2

        // Verify each has independent counts
        assert_eq!(client.message_retry_counts.get(key1).await, Some(3));
        assert_eq!(client.message_retry_counts.get(key2).await, Some(1));
        assert_eq!(client.message_retry_counts.get(key3).await, Some(2));
    }

    #[tokio::test]
    async fn test_retry_cache_key_format() {
        // Verify the cache key format is consistent
        let info = create_test_message_info(
            "120363021033254949@g.us",
            "3EB0ABCD1234",
            "5511999998888@s.whatsapp.net",
        );

        let expected_key = format!("{}:{}:{}", info.source.chat, info.id, info.source.sender);
        assert_eq!(
            expected_key,
            "120363021033254949@g.us:3EB0ABCD1234:5511999998888@s.whatsapp.net"
        );

        // Verify key uniqueness for different senders in same group
        let info2 = create_test_message_info(
            "120363021033254949@g.us",
            "3EB0ABCD1234",                 // Same message ID
            "5511888887777@s.whatsapp.net", // Different sender
        );

        let key2 = format!("{}:{}:{}", info2.source.chat, info2.id, info2.source.sender);
        assert_ne!(
            expected_key, key2,
            "Different senders should have different keys"
        );
    }

    /// Test concurrent retry increments are properly serialized.
    ///
    /// The increment operation uses get+insert which is not fully atomic,
    /// but is sufficient since message retry processing is serialized per key
    /// by the per-chat lock. At most 5 increments should succeed.
    #[tokio::test]
    async fn test_concurrent_retry_increments() {
        use tokio::task::JoinSet;

        let client = create_test_client_for_retry_with_id("concurrent").await;
        let cache_key = "concurrent_test:msg:sender";

        // Spawn 10 concurrent increment tasks
        let mut tasks = JoinSet::new();
        for _ in 0..10 {
            let client_clone = client.clone();
            let key = cache_key.to_string();
            tasks.spawn(async move { client_clone.increment_retry_count(&key).await });
        }

        // Collect all results
        let mut results = Vec::new();
        while let Some(result) = tasks.join_next().await {
            if let Ok(count) = result {
                results.push(count);
            }
        }

        // With atomic operations, exactly 5 should succeed and 5 should fail
        let valid_counts: Vec<_> = results.iter().filter(|r| r.is_some()).collect();
        let none_counts: Vec<_> = results.iter().filter(|r| r.is_none()).collect();

        assert_eq!(
            valid_counts.len(),
            5,
            "Exactly 5 increments should succeed with atomic operations"
        );
        assert_eq!(
            none_counts.len(),
            5,
            "Exactly 5 should return None (after max is reached)"
        );

        // Verify the successful increments returned values 1-5
        let mut values: Vec<u8> = valid_counts.iter().filter_map(|r| **r).collect();
        values.sort();
        assert_eq!(
            values,
            vec![1, 2, 3, 4, 5],
            "Successful increments should return 1, 2, 3, 4, 5"
        );

        // Final count should be 5 (max)
        let final_count = client.message_retry_counts.get(cache_key).await;
        assert_eq!(final_count, Some(5), "Final count should be capped at 5");
    }

    #[tokio::test]
    async fn test_high_retry_count_threshold() {
        // Verify HIGH_RETRY_COUNT_THRESHOLD is set correctly
        assert_eq!(
            HIGH_RETRY_COUNT_THRESHOLD, 3,
            "High retry threshold should be 3"
        );
        assert_eq!(MAX_DECRYPT_RETRIES, 5, "Max retries should be 5");
        // Compile-time assertion that threshold < max (avoids clippy warning)
        const _: () = assert!(HIGH_RETRY_COUNT_THRESHOLD < MAX_DECRYPT_RETRIES);
    }

    #[tokio::test]
    async fn test_message_info_creation_for_groups() {
        let info = create_test_message_info(
            "120363021033254949@g.us",
            "MSG123",
            "5511999998888@s.whatsapp.net",
        );

        assert!(
            info.source.is_group,
            "Group JID should be detected as group"
        );
        assert!(
            !info.source.is_from_me,
            "Test messages default to not from me"
        );
        assert_eq!(info.id, "MSG123");
    }

    #[tokio::test]
    async fn test_message_info_creation_for_dm() {
        let info = create_test_message_info(
            "5511999998888@s.whatsapp.net",
            "DM456",
            "5511999998888@s.whatsapp.net",
        );

        assert!(
            !info.source.is_group,
            "DM JID should not be detected as group"
        );
        assert_eq!(info.id, "DM456");
    }

    #[tokio::test]
    async fn test_retry_count_cache_expiration() {
        // Note: This test verifies cache configuration, not actual TTL (which would be slow)
        let client = create_test_client_for_retry_with_id("expiration").await;

        // The cache should have a TTL of 5 minutes (300 seconds) as configured in client.rs
        // We can verify entries are being stored and the cache is functional
        let cache_key = "expiry_test:msg:sender";

        let count = client.increment_retry_count(cache_key).await;
        assert_eq!(count, Some(1));

        // Entry should still exist immediately after
        let stored = client.message_retry_counts.get(cache_key).await;
        assert!(
            stored.is_some(),
            "Entry should exist immediately after insert"
        );
    }

    #[tokio::test]
    async fn test_spawn_retry_receipt_basic_flow() {
        // This is an integration test that verifies spawn_retry_receipt
        // doesn't panic and updates the retry count correctly

        let client = create_test_client_for_retry_with_id("spawn_basic").await;
        let info = create_test_message_info(
            "120363021033254949@g.us",
            "SPAWN_TEST_MSG",
            "5511999998888@s.whatsapp.net",
        );

        let cache_key = format!("{}:{}:{}", info.source.chat, info.id, info.source.sender);

        // Verify count starts at 0
        assert!(
            client.message_retry_counts.get(&cache_key).await.is_none(),
            "Cache should be empty initially"
        );

        // Call spawn_retry_receipt (this spawns a task, so we need to wait)
        client.spawn_retry_receipt(&info, RetryReason::UnknownError);

        // Give the spawned task time to execute
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Verify count was incremented (the actual send will fail due to no connection, but count should update)
        let stored = client.message_retry_counts.get(&cache_key).await;
        assert_eq!(stored, Some(1), "Retry count should be 1 after spawn");
    }

    #[tokio::test]
    async fn test_spawn_retry_receipt_respects_max_retries() {
        let client = create_test_client_for_retry_with_id("spawn_max").await;
        let info = create_test_message_info(
            "120363021033254949@g.us",
            "MAX_RETRY_TEST",
            "5511999998888@s.whatsapp.net",
        );

        let cache_key = format!("{}:{}:{}", info.source.chat, info.id, info.source.sender);

        // Pre-fill cache to max retries
        client
            .message_retry_counts
            .insert(cache_key.clone(), MAX_DECRYPT_RETRIES)
            .await;

        // Verify count is at max
        assert_eq!(
            client.message_retry_counts.get(&cache_key).await,
            Some(MAX_DECRYPT_RETRIES)
        );

        // Call spawn_retry_receipt - should NOT increment (already at max)
        client.spawn_retry_receipt(&info, RetryReason::UnknownError);

        // Give the spawned task time to execute
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Count should still be at max (not incremented)
        let stored = client.message_retry_counts.get(&cache_key).await;
        assert_eq!(
            stored,
            Some(MAX_DECRYPT_RETRIES),
            "Count should remain at max"
        );
    }

    #[tokio::test]
    async fn test_pdo_cache_key_format_matches() {
        // PDO uses "{chat}:{msg_id}" format
        // Retry uses "{chat}:{msg_id}:{sender}" format
        // They are intentionally different to track independently

        let info = create_test_message_info(
            "120363021033254949@g.us",
            "PDO_KEY_TEST",
            "5511999998888@s.whatsapp.net",
        );

        let retry_key = format!("{}:{}:{}", info.source.chat, info.id, info.source.sender);
        let pdo_key = format!("{}:{}", info.source.chat, info.id);

        assert_ne!(retry_key, pdo_key, "PDO and retry keys should be different");
        assert!(
            retry_key.starts_with(&pdo_key),
            "Retry key should start with PDO key pattern"
        );
    }

    #[tokio::test]
    async fn test_multiple_senders_same_message_id_tracked_separately() {
        // In a group, multiple senders could theoretically have the same message ID
        // (unlikely but the system should handle it)

        let client = create_test_client_for_retry_with_id("multi_sender").await;

        let group = "120363021033254949@g.us";
        let msg_id = "SAME_MSG_ID";
        let sender1 = "5511111111111@s.whatsapp.net";
        let sender2 = "5522222222222@s.whatsapp.net";

        let key1 = format!("{}:{}:{}", group, msg_id, sender1);
        let key2 = format!("{}:{}:{}", group, msg_id, sender2);

        // Increment for sender1 multiple times
        client.increment_retry_count(&key1).await;
        client.increment_retry_count(&key1).await;
        client.increment_retry_count(&key1).await;

        // Increment for sender2 once
        client.increment_retry_count(&key2).await;

        // Verify independent tracking
        assert_eq!(
            client.message_retry_counts.get(&key1).await,
            Some(3),
            "Sender1 should have 3 retries"
        );
        assert_eq!(
            client.message_retry_counts.get(&key2).await,
            Some(1),
            "Sender2 should have 1 retry"
        );
    }

    /// Test: Verify JID type detection for status broadcasts, broadcast lists, groups, and users.
    #[test]
    fn test_status_broadcast_jid_detection() {
        use wacore_binary::jid::{Jid, JidExt};

        let status_jid: Jid = "status@broadcast".parse().expect("status JID should parse");
        assert!(status_jid.is_status_broadcast());

        let broadcast_list: Jid = "123456789@broadcast"
            .parse()
            .expect("broadcast JID should parse");
        assert!(!broadcast_list.is_status_broadcast());
        assert!(broadcast_list.is_broadcast_list());

        let group_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("group JID should parse");
        assert!(!group_jid.is_status_broadcast());

        let user_jid: Jid = "15551234567@s.whatsapp.net"
            .parse()
            .expect("user JID should parse");
        assert!(!user_jid.is_status_broadcast());
    }

    /// Test: Verify should_process_skmsg logic matches WA Web's canDecryptNext pattern.
    ///
    /// WA Web applies canDecryptNext uniformly: if pkmsg fails with a retriable error,
    /// skmsg is skipped regardless of chat type (group, status, 1:1). No exception for
    /// status broadcasts — the retry receipt for the pkmsg will cause the sender to
    /// resend the entire message including SKDM.
    #[test]
    fn test_should_process_skmsg_logic_matches_wa_web() {
        // Test cases: (chat_jid, session_empty, session_success, session_dupe, expected)
        let test_cases = [
            // Status broadcast: same rules as all other chats (WA Web: canDecryptNext is uniform)
            ("status@broadcast", false, false, false, false), // Fail: session failed → skip skmsg
            ("status@broadcast", false, false, true, true),   // OK: duplicate
            ("status@broadcast", false, true, false, true),   // OK: success
            ("status@broadcast", true, false, false, true),   // OK: no session msgs
            // Regular group
            ("120363021033254949@g.us", false, false, false, false),
            ("120363021033254949@g.us", false, false, true, true),
            ("120363021033254949@g.us", false, true, false, true),
            ("120363021033254949@g.us", true, false, false, true),
            // 1:1 chat
            ("15551234567@s.whatsapp.net", false, false, false, false),
            ("15551234567@s.whatsapp.net", true, false, false, true),
        ];

        for (jid_str, session_empty, session_success, session_dupe, expected) in test_cases {
            // Recreate the should_process_skmsg logic from handle_incoming_message
            let should_process_skmsg = session_empty || session_success || session_dupe;

            assert_eq!(
                should_process_skmsg,
                expected,
                "For chat {} with session_empty={}, session_success={}, session_dupe={}: \
                 expected should_process_skmsg={}, got {}",
                jid_str,
                session_empty,
                session_success,
                session_dupe,
                expected,
                should_process_skmsg
            );
        }
    }

    /// Test: parse_message_info returns error when message "id" attribute is missing
    ///
    /// Missing message IDs would cause silent collisions in caches/keys, so this
    /// must be a hard error rather than defaulting to an empty string.
    #[tokio::test]
    async fn test_parse_message_info_missing_id_returns_error() {
        let backend = Arc::new(
            SqliteStore::new("file:memdb_missing_id_test?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("test backend should initialize"),
        );
        let (client, _sync_rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let node = NodeBuilder::new("message")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("t", "1759295366")
            .attr("type", "text")
            .build();

        let result = client.parse_message_info(&node).await;

        assert!(
            result.is_err(),
            "parse_message_info should fail when 'id' is missing"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("id"),
            "Error message should mention missing 'id' attribute: {}",
            err_msg
        );
    }
    #[tokio::test]
    async fn test_no_sender_key_sends_immediate_retry() {
        // Verify that when skmsg decryption fails with NoSenderKeyState,
        // a retry receipt is sent immediately (no delay, no re-queue).
        // This matches WA Web behavior where NoSenderKey → SignalRetryable → RETRY.
        let _ = env_logger::builder().is_test(true).try_init();

        use crate::store::SqliteStore;
        use crate::store::persistence_manager::PersistenceManager;
        use wacore_binary::builder::NodeBuilder;
        use wacore_binary::node::NodeContent;

        let backend = Arc::new(
            SqliteStore::new("file:memdb_retry_immediate?mode=memory&cache=shared")
                .await
                .expect("Failed to create test backend"),
        );
        let pm = Arc::new(
            PersistenceManager::new(backend.clone())
                .await
                .expect("test backend should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm.clone(),
            mock_transport(),
            mock_http_client(),
            None,
        )
        .await;

        let group_jid: Jid = "120363021033254949@g.us".parse().unwrap();
        let sender_jid: Jid = "1234567890:1@s.whatsapp.net".parse().unwrap();
        let msg_id = "TEST_IMMEDIATE_RETRY";

        // Pseudo-valid SenderKeyMessage: Version 3 + Protobuf + Fake Sig (64 bytes)
        let mut content = vec![0x33, 0x08, 0x01, 0x10, 0x01, 0x1A, 0x00];
        content.extend(vec![0u8; 64]);

        let node = NodeBuilder::new("message")
            .attr("id", msg_id)
            .attr("from", group_jid.clone())
            .attr("participant", sender_jid.clone())
            .attr("type", "text")
            .children(vec![{
                let mut n = NodeBuilder::new("enc")
                    .attr("type", "skmsg")
                    .attr("v", "2")
                    .build();
                n.content = Some(NodeContent::Bytes(content));
                n
            }])
            .build();

        client.clone().handle_incoming_message(Arc::new(node)).await;

        // spawn_retry_receipt runs in a spawned task, wait for it
        let retry_key = client
            .make_retry_cache_key(&group_jid, msg_id, &sender_jid)
            .await;
        for _ in 0..20 {
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
            if client.message_retry_counts.get(&retry_key).await.is_some() {
                break;
            }
        }
        assert_eq!(
            client.message_retry_counts.get(&retry_key).await,
            Some(1),
            "NoSenderKeyState should immediately trigger retry receipt (count=1)"
        );
    }

    #[test]
    fn test_is_sender_key_distribution_only() {
        let skdm = wa::message::SenderKeyDistributionMessage {
            group_id: Some("group".into()),
            axolotl_sender_key_distribution_message: Some(vec![1, 2, 3]),
        };

        // Empty message → false (no SKDM)
        assert!(!is_sender_key_distribution_only(&wa::Message::default()));

        // SKDM only → true
        assert!(is_sender_key_distribution_only(&wa::Message {
            sender_key_distribution_message: Some(skdm.clone()),
            ..Default::default()
        }));

        // SKDM + message_context_info → still true (context_info is metadata)
        assert!(is_sender_key_distribution_only(&wa::Message {
            sender_key_distribution_message: Some(skdm.clone()),
            message_context_info: Some(wa::MessageContextInfo::default()),
            ..Default::default()
        }));

        // SKDM + sticker → false (has user content)
        assert!(!is_sender_key_distribution_only(&wa::Message {
            sender_key_distribution_message: Some(skdm.clone()),
            sticker_message: Some(Box::new(wa::message::StickerMessage::default())),
            ..Default::default()
        }));

        // SKDM + text → false (has user content)
        assert!(!is_sender_key_distribution_only(&wa::Message {
            sender_key_distribution_message: Some(skdm.clone()),
            conversation: Some("hello".into()),
            ..Default::default()
        }));

        // protocol_message only (no SKDM) → false
        assert!(!is_sender_key_distribution_only(&wa::Message {
            protocol_message: Some(Box::new(wa::message::ProtocolMessage::default())),
            ..Default::default()
        }));
    }

    /// Test: unwrap_device_sent extracts a reaction from a DeviceSentMessage wrapper.
    #[test]
    fn test_unwrap_device_sent_extracts_reaction() {
        let wrapped = wa::Message {
            device_sent_message: Some(Box::new(wa::message::DeviceSentMessage {
                destination_jid: Some("5511999999999@s.whatsapp.net".to_string()),
                message: Some(Box::new(wa::Message {
                    reaction_message: Some(wa::message::ReactionMessage {
                        text: Some("\u{2764}".to_string()),
                        ..Default::default()
                    }),
                    ..Default::default()
                })),
                phash: None,
            })),
            ..Default::default()
        };

        let unwrapped = unwrap_device_sent(wrapped);
        assert!(
            unwrapped.device_sent_message.is_none(),
            "DSM wrapper should be removed"
        );
        assert_eq!(
            unwrapped
                .reaction_message
                .as_ref()
                .and_then(|r| r.text.as_deref()),
            Some("\u{2764}"),
            "reaction should be accessible after unwrapping"
        );
        assert!(
            !is_sender_key_distribution_only(&unwrapped),
            "unwrapped reaction should not be filtered as SKDM-only"
        );
    }

    /// Test: unwrap_device_sent preserves the wrapper when inner message is None.
    #[test]
    fn test_unwrap_device_sent_preserves_empty_wrapper() {
        let wrapped = wa::Message {
            device_sent_message: Some(Box::new(wa::message::DeviceSentMessage {
                destination_jid: Some("5511999999999@s.whatsapp.net".to_string()),
                message: None,
                phash: None,
            })),
            ..Default::default()
        };

        let result = unwrap_device_sent(wrapped);
        assert!(
            result.device_sent_message.is_some(),
            "empty DSM wrapper should be preserved"
        );
    }

    /// Test: unwrap_device_sent passes through a plain message unchanged.
    #[test]
    fn test_unwrap_device_sent_passthrough() {
        let msg = wa::Message {
            conversation: Some("hello".to_string()),
            ..Default::default()
        };

        let result = unwrap_device_sent(msg);
        assert_eq!(result.conversation.as_deref(), Some("hello"));
    }

    /// Test: unwrap_device_sent merges messageContextInfo from outer and inner,
    /// matching WAWebDeviceSentMessageProtoUtils.unwrapDeviceSentMessage.
    #[test]
    fn test_unwrap_device_sent_merges_context_info() {
        let wrapped = wa::Message {
            // Outer message_context_info (from the DSM envelope)
            message_context_info: Some(wa::MessageContextInfo {
                message_secret: Some(vec![10, 20, 30]),
                limit_sharing_v2: Some(wa::LimitSharing::default()),
                ..Default::default()
            }),
            device_sent_message: Some(Box::new(wa::message::DeviceSentMessage {
                destination_jid: Some("5511999999999@s.whatsapp.net".to_string()),
                message: Some(Box::new(wa::Message {
                    conversation: Some("hello".to_string()),
                    // Inner has its own message_secret but no limit_sharing_v2
                    message_context_info: Some(wa::MessageContextInfo {
                        message_secret: Some(vec![1, 2, 3]),
                        ..Default::default()
                    }),
                    ..Default::default()
                })),
                phash: None,
            })),
            ..Default::default()
        };

        let result = unwrap_device_sent(wrapped);
        let ctx = result.message_context_info.as_ref().unwrap();

        assert_eq!(
            ctx.message_secret,
            Some(vec![1, 2, 3]),
            "inner message_secret should be preferred"
        );
        assert!(
            ctx.limit_sharing_v2.is_some(),
            "limit_sharing_v2 should come from outer (always)"
        );
    }

    /// Test: unwrap_device_sent falls back to outer message_secret when inner has none.
    #[test]
    fn test_unwrap_device_sent_secret_fallback() {
        let wrapped = wa::Message {
            message_context_info: Some(wa::MessageContextInfo {
                message_secret: Some(vec![10, 20, 30]),
                ..Default::default()
            }),
            device_sent_message: Some(Box::new(wa::message::DeviceSentMessage {
                destination_jid: Some("5511999999999@s.whatsapp.net".to_string()),
                message: Some(Box::new(wa::Message {
                    conversation: Some("hello".to_string()),
                    // Inner has no message_context_info at all
                    ..Default::default()
                })),
                phash: None,
            })),
            ..Default::default()
        };

        let result = unwrap_device_sent(wrapped);
        let ctx = result.message_context_info.as_ref().unwrap();
        assert_eq!(
            ctx.message_secret,
            Some(vec![10, 20, 30]),
            "should fall back to outer message_secret"
        );
    }

    #[tokio::test]
    async fn test_parse_edit_attribute_sender_revoke() {
        let client = create_test_client_for_retry_with_id("edit_sender_revoke").await;

        let node = NodeBuilder::new("message")
            .attr("from", "status@broadcast")
            .attr("id", "TEST123")
            .attr("participant", "5551234567@lid")
            .attr("t", "1772895198")
            .attr("type", "text")
            .attr("edit", "7")
            .build();

        let info = client
            .parse_message_info(&node)
            .await
            .expect("parse_message_info should succeed");

        assert_eq!(
            info.edit,
            EditAttribute::SenderRevoke,
            "edit='7' should parse as SenderRevoke"
        );
    }

    #[tokio::test]
    async fn test_parse_edit_attribute_admin_revoke() {
        let client = create_test_client_for_retry_with_id("edit_admin_revoke").await;

        let node = NodeBuilder::new("message")
            .attr("from", "120363999999999999@g.us")
            .attr("id", "TEST456")
            .attr("participant", "5551234567@lid")
            .attr("t", "1772895198")
            .attr("type", "text")
            .attr("edit", "8")
            .build();

        let info = client
            .parse_message_info(&node)
            .await
            .expect("parse_message_info should succeed");

        assert_eq!(
            info.edit,
            EditAttribute::AdminRevoke,
            "edit='8' should parse as AdminRevoke"
        );
    }

    #[tokio::test]
    async fn test_parse_edit_attribute_message_edit() {
        let client = create_test_client_for_retry_with_id("edit_message_edit").await;

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

        let info = client
            .parse_message_info(&node)
            .await
            .expect("parse_message_info should succeed");

        assert_eq!(
            info.edit,
            EditAttribute::MessageEdit,
            "edit='1' should parse as MessageEdit"
        );
    }

    #[tokio::test]
    async fn test_parse_edit_attribute_missing() {
        let client = create_test_client_for_retry_with_id("edit_missing").await;

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

        let info = client
            .parse_message_info(&node)
            .await
            .expect("parse_message_info should succeed");

        assert_eq!(
            info.edit,
            EditAttribute::Empty,
            "missing edit attr should default to Empty"
        );
    }

    #[tokio::test]
    async fn test_revoked_message_still_retries() {
        let client = create_test_client_for_retry_with_id("revoke_retry").await;

        let mut info = create_test_message_info(
            "status@broadcast",
            "REVOKE_MSG1",
            "5551234567@s.whatsapp.net",
        );
        info.edit = EditAttribute::SenderRevoke;

        // WA Web retries revoked messages the same as any other — the revoke
        // protocol message contains the target ID needed to process the deletion
        client.spawn_retry_receipt(&info, RetryReason::NoSession);

        // Wait for the spawned task to execute
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        let cache_key = client
            .make_retry_cache_key(&info.source.chat, &info.id, &info.source.sender)
            .await;
        assert_eq!(
            client.message_retry_counts.get(&cache_key).await,
            Some(1),
            "revoked message should still have retry count 1 (WA Web retries all messages)"
        );
    }

    #[tokio::test]
    async fn test_enc_count_preseeds_retry_cache() {
        let client = create_test_client_for_retry_with_id("enc_preseed").await;

        let chat_jid: Jid = "5551234567@s.whatsapp.net".parse().unwrap();
        let msg_id = "ENC_COUNT_MSG1";

        // Pre-seed via the same logic used in handle_incoming_message
        let max_sender_retry_count: u8 = 3;
        let cache_key = client
            .make_retry_cache_key(&chat_jid, msg_id, &chat_jid)
            .await;
        // Insert only if absent (portable alternative to moka's entry_by_ref().or_insert())
        if client.message_retry_counts.get(&cache_key).await.is_none() {
            client
                .message_retry_counts
                .insert(cache_key.clone(), max_sender_retry_count)
                .await;
        }

        assert_eq!(
            client.message_retry_counts.get(&cache_key).await,
            Some(3),
            "cache should be pre-seeded with sender retry count"
        );
    }

    #[tokio::test]
    async fn test_enc_no_count_cache_empty() {
        let client = create_test_client_for_retry_with_id("enc_no_count").await;

        let chat_jid: Jid = "5551234567@s.whatsapp.net".parse().unwrap();
        let msg_id = "ENC_NO_COUNT_MSG1";

        // When max_sender_retry_count is 0, no pre-seeding occurs
        let max_sender_retry_count: u8 = 0;
        if max_sender_retry_count > 0 {
            let cache_key = client
                .make_retry_cache_key(&chat_jid, msg_id, &chat_jid)
                .await;
            if client.message_retry_counts.get(&cache_key).await.is_none() {
                client
                    .message_retry_counts
                    .insert(cache_key, max_sender_retry_count)
                    .await;
            }
        }

        let cache_key = client
            .make_retry_cache_key(&chat_jid, msg_id, &chat_jid)
            .await;
        assert!(
            client.message_retry_counts.get(&cache_key).await.is_none(),
            "cache should be empty when no count attribute"
        );
    }

    #[tokio::test]
    async fn test_enc_count_does_not_overwrite_higher() {
        let client = create_test_client_for_retry_with_id("enc_no_overwrite").await;

        let chat_jid: Jid = "5551234567@s.whatsapp.net".parse().unwrap();
        let msg_id = "ENC_NOOVERWRITE_MSG1";

        let cache_key = client
            .make_retry_cache_key(&chat_jid, msg_id, &chat_jid)
            .await;

        // Pre-insert a higher value
        client
            .message_retry_counts
            .insert(cache_key.clone(), 4)
            .await;

        // max(existing, incoming) should NOT overwrite with a lower value
        let max_sender_retry_count: u8 = 2;
        let existing = client
            .message_retry_counts
            .get(&cache_key)
            .await
            .unwrap_or(0);
        if max_sender_retry_count > existing {
            client
                .message_retry_counts
                .insert(cache_key.clone(), max_sender_retry_count)
                .await;
        }

        assert_eq!(
            client.message_retry_counts.get(&cache_key).await,
            Some(4),
            "should not overwrite existing higher value"
        );
    }

    #[tokio::test]
    async fn test_enc_count_updates_when_sender_higher() {
        let client = create_test_client_for_retry_with_id("enc_update_higher").await;

        let chat_jid: Jid = "5551234567@s.whatsapp.net".parse().unwrap();
        let msg_id = "ENC_UPDATE_MSG1";

        let cache_key = client
            .make_retry_cache_key(&chat_jid, msg_id, &chat_jid)
            .await;

        // Pre-insert a lower value
        client
            .message_retry_counts
            .insert(cache_key.clone(), 1)
            .await;

        // max(existing, incoming) SHOULD update with a higher value
        let max_sender_retry_count: u8 = 3;
        let existing = client
            .message_retry_counts
            .get(&cache_key)
            .await
            .unwrap_or(0);
        if max_sender_retry_count > existing {
            client
                .message_retry_counts
                .insert(cache_key.clone(), max_sender_retry_count)
                .await;
        }

        assert_eq!(
            client.message_retry_counts.get(&cache_key).await,
            Some(3),
            "should update to higher sender count"
        );
    }
}