rvoip-sip 0.2.4

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
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
//! Simplified Dialog Adapter for rvoip-sip
//!
//! Thin translation layer between dialog-core and state machine.
//! Focuses only on essential dialog operations and events.
//!
//! ## API Design
//!
//! This adapter provides a clean interface for dialog operations:
//!
//! ### Primary Methods
//! - `send_invite_with_details()` - Creates dialog and sends INVITE in one atomic operation
//! - `send_response()` - Sends SIP responses for incoming calls
//! - `send_bye()` - Terminates calls
//! - `send_ack()` - Acknowledges responses
//!
//! ### Removed Methods
//! The following methods were removed to avoid confusion:
//! - `create_dialog()` - Did not actually create a dialog in dialog-core
//! - `send_invite()` - Did not actually send an INVITE
//!
//! All dialog creation is now done through `send_invite_with_details()` which
//! properly creates the dialog in dialog-core and sends the INVITE.

use crate::api::types::DialogIdentity;
use crate::cleanup_diag::{self, CleanupStage};
use crate::errors::{Result, SessionError};
use crate::session_store::SessionStore;
use crate::state_table::types::{DialogId, SessionId};
use dashmap::DashMap;
use rvoip_infra_common::events::{
    coordinator::GlobalEventCoordinator,
    cross_crate::{RvoipCrossCrateEvent, SessionToDialogEvent},
};
use rvoip_sip_core::{Response, StatusCode, Uri};
use rvoip_sip_dialog::{
    api::unified::{
        ByeRequestOptions, CancelRequestOptions, InfoRequestOptions, MessageRequestOptions,
        NotifyRequestOptions, ReferRequestOptions, SubscribeRequestOptions, UnifiedDialogApi,
        UpdateRequestOptions,
    },
    transaction::TransactionKey,
    DialogId as RvoipDialogId,
};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Registrar metadata returned on a successful REGISTER 2xx response.
#[derive(Debug, Clone, Default)]
pub(crate) struct RegistrationResponseMetadata {
    pub(crate) service_route: Option<Vec<String>>,
    pub(crate) pub_gruu: Option<String>,
    pub(crate) temp_gruu: Option<String>,
}

/// Outcome for a single REGISTER wire attempt.
///
/// This deliberately does not encode state-machine lifecycle decisions. The
/// dialog adapter sends one request, parses one response, and returns the SIP
/// result; the state-machine action decides which internal event to enqueue.
#[derive(Debug, Clone)]
pub(crate) enum RegisterAttemptOutcome {
    Registered {
        accepted_expires: u32,
        metadata: RegistrationResponseMetadata,
    },
    Unregistered,
    AuthChallenge {
        status_code: u16,
        challenge: String,
    },
    IntervalTooBrief {
        min_expires: u32,
    },
    Failure {
        status_code: u16,
        reason: String,
    },
}

/// Minimal dialog adapter - just translates between dialog-core and state machine
pub struct DialogAdapter {
    /// Dialog-core unified API
    pub(crate) dialog_api: Arc<UnifiedDialogApi>,

    /// Session store for updating IDs
    pub(crate) store: Arc<SessionStore>,

    /// Simple mapping of session IDs to dialog IDs
    pub(crate) session_to_dialog: Arc<DashMap<SessionId, RvoipDialogId>>,
    pub(crate) dialog_to_session: Arc<DashMap<RvoipDialogId, SessionId>>,

    /// Store Call-ID to session mapping for correlation
    pub(crate) callid_to_session: Arc<DashMap<String, SessionId>>,

    /// Store outgoing INVITE transaction IDs for UAC ACK sending
    pub(crate) outgoing_invite_tx: Arc<DashMap<SessionId, TransactionKey>>,

    /// SIP_API_DESIGN_2 §7.4 — application-supplied headers stamped on
    /// every outbound message the state machine emits automatically
    /// (auto-BYE on session-timer expiry, auto-CANCEL on
    /// dialog-terminated-during-INVITE, auto-NOTIFY on REFER
    /// completion). Populated at construction from
    /// [`crate::Config::auto_emit_extra_headers`]; empty by default.
    pub(crate) auto_emit_extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,

    /// Global event coordinator for publishing events
    pub(crate) global_coordinator: Arc<GlobalEventCoordinator>,

    /// State machine reference for triggering events (needed for REGISTER
    /// response handling). Wired post-construction via
    /// [`DialogAdapter::init_state_machine`] because the `StateMachine`
    /// transitively depends on this adapter — classic circular init. The
    /// `OnceLock` makes the initialization soundly observable by any task
    /// without requiring `&mut self`.
    pub(crate) state_machine: Arc<std::sync::OnceLock<Arc<crate::state_machine::StateMachine>>>,

    /// RFC 3261 §8.1.2 outbound proxy URI, validated at construction. When
    /// `Some`, `send_invite_with_extra_headers` prepends a `Route:
    /// <proxy-uri;lr>` header so dialog-initiating requests traverse the
    /// configured proxy. `None` → no Route pre-loading. Populated from
    /// [`crate::Config::outbound_proxy_uri`] during coordinator setup.
    pub(crate) outbound_proxy_uri: Option<rvoip_sip_core::types::uri::Uri>,

    /// RFC 5626 §4 outbound registration params (`+sip.instance` URN +
    /// `reg-id`) applied to REGISTER Contact headers, together with the
    /// `;ob` URI flag. `None` → pre-5626 behaviour. Populated at
    /// construction from
    /// [`crate::Config::sip_outbound_enabled`]+[`crate::Config::sip_instance`].
    pub(crate) outbound_contact_params:
        Option<rvoip_sip_core::types::outbound::OutboundContactParams>,

    /// Symmetric registered-flow keep-alive identity. Unlike RFC 5626 mode,
    /// this starts after REGISTER success even if the registrar does not echo
    /// outbound Contact parameters.
    pub(crate) symmetric_flow_params:
        Option<rvoip_sip_core::types::outbound::OutboundContactParams>,

    /// Automatic registration refresh settings and task registry.
    registration_auto_refresh: bool,
    registration_refresh_jitter_percent: u8,
    registration_refresh_tasks: Arc<DashMap<SessionId, tokio::task::AbortHandle>>,

    /// Perf diagnostics for dialog mapping cleanup balance.
    cleanup_attempt_total: Arc<AtomicU64>,
    cleanup_mapped_total: Arc<AtomicU64>,
    cleanup_missing_total: Arc<AtomicU64>,
    cleanup_call_ids_removed_total: Arc<AtomicU64>,
    cleanup_outgoing_invite_removed_total: Arc<AtomicU64>,

    /// SIP_API_DESIGN_2 §12.4 — pluggable trace-output redactor. When
    /// `Some`, the trace path consults this hook before emitting each
    /// header to the trace sink so PII / carrier tokens can be
    /// scrubbed without affecting the wire form. Populated at
    /// construction from
    /// [`crate::Config::trace_redaction`]; `None` keeps the legacy
    /// log-verbatim behaviour. See
    /// [`crate::TraceRedactor`] for the policy contract.
    pub(crate) trace_redactor: Option<Arc<dyn crate::api::trace_redactor::TraceRedactor>>,
}

impl DialogAdapter {
    /// Create a new dialog adapter.
    ///
    /// `outbound_proxy_uri` is the RFC 3261 §8.1.2 outbound proxy, if any.
    /// Pass `None` for no pre-loaded Route. When `Some`, the URI MUST parse
    /// as a valid SIP URI — typically `sip:sbc.example.com;lr`.
    ///
    /// `outbound_contact_params` is the RFC 5626 §4 instance + reg-id pair
    /// attached to REGISTER Contact headers when outbound registration is
    /// enabled. Pass `None` for pre-5626 REGISTER Contact shape.
    pub fn new(
        dialog_api: Arc<UnifiedDialogApi>,
        store: Arc<SessionStore>,
        global_coordinator: Arc<GlobalEventCoordinator>,
        outbound_proxy_uri: Option<rvoip_sip_core::types::uri::Uri>,
        outbound_contact_params: Option<rvoip_sip_core::types::outbound::OutboundContactParams>,
        symmetric_flow_params: Option<rvoip_sip_core::types::outbound::OutboundContactParams>,
        registration_auto_refresh: bool,
        registration_refresh_jitter_percent: u8,
        auto_emit_extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
        trace_redactor: Option<Arc<dyn crate::api::trace_redactor::TraceRedactor>>,
    ) -> Self {
        Self {
            dialog_api,
            store,
            session_to_dialog: Arc::new(DashMap::new()),
            dialog_to_session: Arc::new(DashMap::new()),
            callid_to_session: Arc::new(DashMap::new()),
            outgoing_invite_tx: Arc::new(DashMap::new()),
            auto_emit_extra_headers,
            global_coordinator,
            state_machine: Arc::new(std::sync::OnceLock::new()),
            outbound_proxy_uri,
            outbound_contact_params,
            symmetric_flow_params,
            registration_auto_refresh,
            registration_refresh_jitter_percent,
            registration_refresh_tasks: Arc::new(DashMap::new()),
            cleanup_attempt_total: Arc::new(AtomicU64::new(0)),
            cleanup_mapped_total: Arc::new(AtomicU64::new(0)),
            cleanup_missing_total: Arc::new(AtomicU64::new(0)),
            cleanup_call_ids_removed_total: Arc::new(AtomicU64::new(0)),
            cleanup_outgoing_invite_removed_total: Arc::new(AtomicU64::new(0)),
            trace_redactor,
        }
    }

    /// Wire the state machine after construction. Idempotent — subsequent
    /// calls are silently ignored (returns `Err` if already set, which
    /// callers may choose to ignore or treat as a programming error).
    pub fn init_state_machine(
        &self,
        state_machine: Arc<crate::state_machine::StateMachine>,
    ) -> std::result::Result<(), Arc<crate::state_machine::StateMachine>> {
        self.state_machine.set(state_machine)
    }

    fn publish_api_event(&self, api_event: crate::api::events::Event) {
        let wrapped = crate::adapters::SessionApiCrossCrateEvent::new(api_event);
        let coordinator = self.global_coordinator.clone();
        tokio::spawn(async move {
            if let Err(e) = coordinator.publish(wrapped).await {
                tracing::warn!("Failed to publish app-level dialog adapter event: {}", e);
            }
        });
    }

    pub(crate) fn outbound_transport_context_for_uri(
        &self,
        request_uri: &str,
    ) -> crate::auth::SipTransportSecurityContext {
        let Ok(uri) = Uri::from_str(request_uri) else {
            return crate::auth::SipTransportSecurityContext::from_request_uri_transport_hint(
                request_uri,
            );
        };
        let transaction_manager = self
            .dialog_api
            .dialog_manager()
            .core()
            .transaction_manager();
        let transport = transaction_manager.get_best_transport_for_uri(&uri);
        let mut context =
            crate::auth::SipTransportSecurityContext::from_transport_name(transport.to_string());
        if let Some(info) = transaction_manager.get_transport_info(transport) {
            context.local_addr = info.local_addr.map(|addr| addr.to_string());
        }
        context
    }

    pub(crate) fn outbound_transport_context_for_response(
        &self,
        response: &Response,
        fallback_request_uri: &str,
    ) -> crate::auth::SipTransportSecurityContext {
        self.dialog_api
            .outbound_transport_context_for_response(response)
            .map(|context| {
                crate::auth::SipTransportSecurityContext::from_transport_context(&context)
            })
            .unwrap_or_else(|| self.outbound_transport_context_for_uri(fallback_request_uri))
    }

    pub(crate) fn abort_registration_refresh(&self, session_id: &SessionId) {
        let guard = cleanup_diag::stage_guard(CleanupStage::TimerTaskShutdown, &session_id.0);
        if let Some((_, handle)) = self.registration_refresh_tasks.remove(session_id) {
            handle.abort();
        }
        guard.finish_success();
    }

    /// Feature-gated retained-object counts for perf leak investigations.
    #[cfg(feature = "perf-tests")]
    pub(crate) fn perf_diagnostic_counts(&self) -> serde_json::Value {
        serde_json::json!({
            "session_to_dialog": self.session_to_dialog.len(),
            "dialog_to_session": self.dialog_to_session.len(),
            "callid_to_session": self.callid_to_session.len(),
            "outgoing_invite_tx": self.outgoing_invite_tx.len(),
            "registration_refresh_tasks": self.registration_refresh_tasks.len(),
            "lifecycle": {
                "cleanup_attempt_total": self.cleanup_attempt_total.load(Ordering::Relaxed),
                "cleanup_mapped_total": self.cleanup_mapped_total.load(Ordering::Relaxed),
                "cleanup_missing_total": self.cleanup_missing_total.load(Ordering::Relaxed),
                "cleanup_call_ids_removed_total": self.cleanup_call_ids_removed_total.load(Ordering::Relaxed),
                "cleanup_outgoing_invite_removed_total": self.cleanup_outgoing_invite_removed_total.load(Ordering::Relaxed),
            },
        })
    }

    pub(crate) fn abort_all_registration_refreshes(&self) {
        let guard = cleanup_diag::stage_guard(CleanupStage::TimerTaskShutdown, "all");
        let handles: Vec<_> = self
            .registration_refresh_tasks
            .iter()
            .map(|entry| entry.value().clone())
            .collect();
        self.registration_refresh_tasks.clear();
        for handle in handles {
            handle.abort();
        }
        guard.finish_success();
    }

    fn compute_registration_refresh_at(&self, now: Instant, accepted_expires: u32) -> Instant {
        let base_secs = ((accepted_expires as f64) * 0.85).floor().max(1.0) as u64;
        let jitter_cap_secs =
            (base_secs * u64::from(self.registration_refresh_jitter_percent)) / 100;
        let jitter_secs = if jitter_cap_secs == 0 {
            0
        } else {
            use rand::Rng;
            rand::thread_rng().gen_range(0..=jitter_cap_secs)
        };
        now + Duration::from_secs(base_secs.saturating_sub(jitter_secs).max(1))
    }

    fn schedule_registration_refresh(
        &self,
        session_id: SessionId,
        next_refresh_at: Option<Instant>,
    ) {
        self.abort_registration_refresh(&session_id);

        if !self.registration_auto_refresh {
            return;
        }

        let Some(next_refresh_at) = next_refresh_at else {
            return;
        };
        let Some(state_machine) = self.state_machine.get().cloned() else {
            return;
        };

        let session_id_for_task = session_id.clone();
        let tasks = self.registration_refresh_tasks.clone();
        let adapter = self.clone();
        let handle = tokio::spawn(async move {
            tokio::time::sleep_until(tokio::time::Instant::from_std(next_refresh_at)).await;
            tasks.remove(&session_id_for_task);

            match state_machine
                .process_event(
                    &session_id_for_task,
                    crate::state_table::types::EventType::RefreshRegistration,
                )
                .await
            {
                Ok(result) if result.transition.is_some() => {}
                Ok(_) => {
                    tracing::warn!(
                        "Automatic registration refresh had no state-table transition for session {}; falling back to direct REGISTER",
                        session_id_for_task
                    );
                    if let Err(e) = adapter
                        .send_registration_refresh_direct(&session_id_for_task)
                        .await
                    {
                        tracing::warn!(
                            "Automatic direct registration refresh failed for session {}: {}",
                            session_id_for_task,
                            e
                        );
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "Automatic registration refresh failed for session {}: {}",
                        session_id_for_task,
                        e
                    );
                }
            }
        })
        .abort_handle();

        self.registration_refresh_tasks.insert(session_id, handle);
    }

    async fn send_registration_refresh_direct(&self, session_id: &SessionId) -> Result<()> {
        let session = self.store.get_session(session_id).await?;
        if !session.is_registered {
            tracing::debug!(
                "Skipping automatic registration refresh for unregistered session {}",
                session_id
            );
            return Ok(());
        }

        let from_uri = session
            .local_uri
            .clone()
            .ok_or_else(|| SessionError::InternalError("local_uri not set for refresh".into()))?;
        let registrar_uri = session
            .registrar_uri
            .clone()
            .or_else(|| session.remote_uri.clone())
            .ok_or_else(|| {
                SessionError::InternalError("registrar_uri not set for refresh".into())
            })?;
        let contact_uri = session
            .registration_contact
            .clone()
            .or_else(|| session.local_uri.clone())
            .ok_or_else(|| SessionError::InternalError("contact_uri not set for refresh".into()))?;
        let expires = session.registration_expires.unwrap_or(3600);
        let auth = session
            .auth
            .clone()
            .or_else(|| session.credentials.clone().map(Into::into));
        drop(session);

        let mut attempt_expires = expires;
        for _ in 0..=2 {
            match self
                .send_register(
                    session_id,
                    &registrar_uri,
                    &from_uri,
                    &contact_uri,
                    attempt_expires,
                    auth.as_ref(),
                    Vec::new(),
                )
                .await?
            {
                RegisterAttemptOutcome::Registered {
                    accepted_expires,
                    metadata,
                } => {
                    return self
                        .apply_registration_success(
                            session_id,
                            &registrar_uri,
                            &from_uri,
                            &contact_uri,
                            accepted_expires,
                            metadata,
                        )
                        .await;
                }
                RegisterAttemptOutcome::IntervalTooBrief { min_expires } => {
                    let mut session = self.store.get_session(session_id).await?;
                    session.registration_expires = Some(min_expires);
                    session.registration_retry_count += 1;
                    self.store.update_session(session).await?;
                    attempt_expires = min_expires;
                }
                RegisterAttemptOutcome::Failure {
                    status_code,
                    reason,
                } => {
                    return self
                        .apply_registration_failure(session_id, &registrar_uri, status_code, reason)
                        .await;
                }
                RegisterAttemptOutcome::AuthChallenge { status_code, .. } => {
                    return self
                        .apply_registration_failure(
                            session_id,
                            &registrar_uri,
                            status_code,
                            "automatic registration refresh received a new auth challenge",
                        )
                        .await;
                }
                RegisterAttemptOutcome::Unregistered => {
                    return self
                        .apply_unregistration_success(session_id, &registrar_uri)
                        .await;
                }
            }
        }

        self.apply_registration_failure(
            session_id,
            &registrar_uri,
            423,
            "registration refresh failed with repeated 423 Interval Too Brief responses",
        )
        .await
    }

    pub(crate) fn accepted_registration_expires(
        response: &Response,
        requested_contact_uri: &str,
        fallback_expires: u32,
    ) -> u32 {
        use rvoip_sip_core::types::headers::HeaderAccess;
        use rvoip_sip_core::types::{header::HeaderName, TypedHeader};

        let requested = requested_contact_uri.trim().trim_matches(['<', '>']);

        let mut first_contact_expires = None;
        for contact in response.headers.iter().filter_map(|header| match header {
            TypedHeader::Contact(contact) => Some(contact),
            _ => None,
        }) {
            for address in contact.addresses() {
                let expires = address
                    .get_param("expires")
                    .flatten()
                    .and_then(|value| value.parse::<u32>().ok());
                if first_contact_expires.is_none() {
                    first_contact_expires = expires;
                }
                if address.uri.to_string() == requested {
                    if let Some(expires) = expires {
                        return expires;
                    }
                }
            }
        }

        first_contact_expires
            .or_else(|| {
                response
                    .raw_header_value(&HeaderName::Expires)
                    .and_then(|value| value.trim().parse::<u32>().ok())
            })
            .unwrap_or(fallback_expires)
    }

    pub(crate) fn response_registration_metadata(
        response: &Response,
    ) -> RegistrationResponseMetadata {
        use rvoip_sip_core::types::outbound::read_gruu_contact_params;
        use rvoip_sip_core::types::TypedHeader;

        let service_route = {
            let routes: Vec<String> = response
                .headers
                .iter()
                .filter_map(|header| match header {
                    TypedHeader::ServiceRoute(route) => Some(route.uris()),
                    _ => None,
                })
                .flatten()
                .map(|uri| uri.to_string())
                .collect();
            if routes.is_empty() {
                None
            } else {
                Some(routes)
            }
        };

        let mut pub_gruu = None;
        let mut temp_gruu = None;
        for contact in response.headers.iter().filter_map(|header| match header {
            TypedHeader::Contact(contact) => Some(contact),
            _ => None,
        }) {
            for address in contact.addresses() {
                let params = read_gruu_contact_params(address);
                if pub_gruu.is_none() {
                    pub_gruu = params.pub_gruu;
                }
                if temp_gruu.is_none() {
                    temp_gruu = params.temp_gruu;
                }
            }
        }

        RegistrationResponseMetadata {
            service_route,
            pub_gruu,
            temp_gruu,
        }
    }

    pub(crate) fn register_attempt_outcome_from_response(
        response: &Response,
        contact_uri: &str,
        expires: u32,
    ) -> RegisterAttemptOutcome {
        match response.status_code() {
            200..=299 => {
                if expires == 0 {
                    RegisterAttemptOutcome::Unregistered
                } else {
                    RegisterAttemptOutcome::Registered {
                        accepted_expires: Self::accepted_registration_expires(
                            response,
                            contact_uri,
                            expires,
                        ),
                        metadata: Self::response_registration_metadata(response),
                    }
                }
            }
            401 | 407 => {
                use rvoip_sip_core::types::headers::HeaderAccess;
                let header_name = if response.status_code() == 407 {
                    rvoip_sip_core::types::header::HeaderName::ProxyAuthenticate
                } else {
                    rvoip_sip_core::types::header::HeaderName::WwwAuthenticate
                };
                if let Some(challenge) = response.raw_header_value(&header_name) {
                    RegisterAttemptOutcome::AuthChallenge {
                        status_code: response.status_code(),
                        challenge,
                    }
                } else {
                    RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "REGISTER challenge response did not include challenge header"
                            .to_string(),
                    }
                }
            }
            423 => {
                use rvoip_sip_core::types::headers::HeaderAccess;
                match response
                    .raw_header_value(&rvoip_sip_core::types::header::HeaderName::MinExpires)
                    .and_then(|s| s.trim().parse::<u32>().ok())
                {
                    Some(min_expires) if min_expires > 0 && min_expires <= 7200 => {
                        RegisterAttemptOutcome::IntervalTooBrief { min_expires }
                    }
                    Some(min_expires) => RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: format!(
                            "423 Interval Too Brief included invalid Min-Expires={}",
                            min_expires
                        ),
                    },
                    None => RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "423 Interval Too Brief without Min-Expires header".to_string(),
                    },
                }
            }
            _ => RegisterAttemptOutcome::Failure {
                status_code: response.status_code(),
                reason: response.reason_phrase().to_string(),
            },
        }
    }

    pub(crate) async fn apply_registration_success(
        &self,
        session_id: &SessionId,
        registrar_uri: &str,
        from_uri: &str,
        contact_uri: &str,
        accepted_expires: u32,
        metadata: RegistrationResponseMetadata,
    ) -> Result<()> {
        let now = Instant::now();
        let next_refresh_at = if self.registration_auto_refresh && accepted_expires > 0 {
            Some(self.compute_registration_refresh_at(now, accepted_expires))
        } else {
            None
        };

        let mut session = self.store.get_session(session_id).await?;
        session.is_registered = true;
        session.registration_expires = Some(accepted_expires);
        session.registration_accepted_expires = Some(accepted_expires);
        session.registration_registered_at = Some(now);
        session.registration_next_refresh_at = next_refresh_at;
        session.registration_last_failure = None;
        session.registration_retry_count = 0;
        session.registration_service_route = metadata.service_route;
        session.registration_pub_gruu = metadata.pub_gruu;
        session.registration_temp_gruu = metadata.temp_gruu;
        self.store.update_session(session).await?;

        tracing::info!(
            "✅ Registration successful - session {} marked as registered",
            session_id.0
        );
        self.publish_api_event(crate::api::events::Event::RegistrationSuccess {
            registrar: registrar_uri.to_string(),
            expires: accepted_expires,
            contact: contact_uri.to_string(),
        });
        self.schedule_registration_refresh(session_id.clone(), next_refresh_at);
        self.start_symmetric_registration_keepalive(from_uri, registrar_uri)
            .await;
        Ok(())
    }

    pub(crate) async fn apply_unregistration_success(
        &self,
        session_id: &SessionId,
        registrar_uri: &str,
    ) -> Result<()> {
        self.abort_registration_refresh(session_id);
        let mut session = self.store.get_session(session_id).await?;
        session.is_registered = false;
        session.registration_accepted_expires = None;
        session.registration_registered_at = None;
        session.registration_next_refresh_at = None;
        session.registration_last_failure = None;
        session.registration_retry_count = 0;
        session.registration_service_route = None;
        session.registration_pub_gruu = None;
        session.registration_temp_gruu = None;
        self.store.update_session(session).await?;

        tracing::info!(
            "✅ Unregistration successful - session {} marked as unregistered",
            session_id.0
        );
        self.publish_api_event(crate::api::events::Event::UnregistrationSuccess {
            registrar: registrar_uri.to_string(),
        });
        Ok(())
    }

    pub(crate) async fn apply_registration_failure(
        &self,
        session_id: &SessionId,
        registrar_uri: &str,
        status_code: u16,
        reason: impl Into<String>,
    ) -> Result<()> {
        self.abort_registration_refresh(session_id);
        let reason = reason.into();
        let mut session = self.store.get_session(session_id).await?;
        let failure_summary = if session.registration_retry_count > 0 {
            format!(
                "{} after {} retry attempt(s)",
                reason, session.registration_retry_count
            )
        } else {
            reason.clone()
        };
        session.is_registered = false;
        session.registration_accepted_expires = None;
        session.registration_registered_at = None;
        session.registration_next_refresh_at = None;
        session.registration_last_failure = Some(failure_summary.clone());
        session.registration_service_route = None;
        session.registration_pub_gruu = None;
        session.registration_temp_gruu = None;
        self.store.update_session(session).await?;

        self.publish_api_event(crate::api::events::Event::RegistrationFailed {
            registrar: registrar_uri.to_string(),
            status_code,
            reason: failure_summary,
        });
        Ok(())
    }

    pub(crate) async fn apply_unregistration_failure(
        &self,
        session_id: &SessionId,
        registrar_uri: &str,
        reason: impl Into<String>,
    ) -> Result<()> {
        self.abort_registration_refresh(session_id);
        let reason = reason.into();
        let mut session = self.store.get_session(session_id).await?;
        session.is_registered = false;
        session.registration_accepted_expires = None;
        session.registration_registered_at = None;
        session.registration_next_refresh_at = None;
        session.registration_last_failure = Some(reason.clone());
        session.registration_retry_count = 0;
        session.registration_service_route = None;
        session.registration_pub_gruu = None;
        session.registration_temp_gruu = None;
        self.store.update_session(session).await?;

        self.publish_api_event(crate::api::events::Event::UnregistrationFailed {
            registrar: registrar_uri.to_string(),
            reason,
        });
        Ok(())
    }

    // ===== Direct Dialog Operations =====
    // NOTE: Removed confusing create_dialog() and send_invite() methods
    // Use send_invite_with_details() to create a dialog and send INVITE in one operation

    /// Send a response
    pub async fn send_response_by_dialog(
        &self,
        _dialog_id: DialogId,
        status_code: u16,
        _reason: &str,
    ) -> Result<()> {
        // We can't really convert a string to RvoipDialogId which wraps a UUID
        // This method needs to be rethought - for now just return Ok
        // since this is called from places where we have only our DialogId
        tracing::warn!(
            "send_response_by_dialog called but conversion not implemented - status: {}",
            status_code
        );
        Ok(())
    }

    /// Send BYE for a specific dialog
    pub async fn send_bye(&self, dialog_id: crate::types::DialogId) -> Result<()> {
        // Convert our DialogId to RvoipDialogId
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();

        // Find session ID from dialog
        if let Some(entry) = self.dialog_to_session.get(&rvoip_dialog_id) {
            let session_id = entry.value().clone();
            drop(entry);

            // Send BYE through dialog API
            self.dialog_api
                .send_bye_with_options(&rvoip_dialog_id, ByeRequestOptions::default())
                .await
                .map_err(|e| SessionError::DialogError(format!("Failed to send BYE: {}", e)))?;

            tracing::info!("Sent BYE for session {}", session_id.0);
        } else {
            tracing::warn!("No session found for dialog {}", dialog_id);
        }

        Ok(())
    }

    /// Send re-INVITE with new SDP
    pub async fn send_reinvite(
        &self,
        dialog_id: crate::types::DialogId,
        sdp: String,
    ) -> Result<()> {
        // Convert our DialogId to RvoipDialogId
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();

        // Find session ID from dialog
        if let Some(entry) = self.dialog_to_session.get(&rvoip_dialog_id) {
            let session_id = entry.value().clone();
            drop(entry);

            // Use UPDATE method for re-INVITE
            self.dialog_api
                .send_update_with_options(
                    &rvoip_dialog_id,
                    UpdateRequestOptions {
                        sdp: Some(sdp),
                        ..Default::default()
                    },
                )
                .await
                .map_err(|e| {
                    SessionError::DialogError(format!("Failed to send re-INVITE: {}", e))
                })?;

            tracing::info!("Sent re-INVITE for session {}", session_id.0);
        } else {
            tracing::warn!("No session found for dialog {}", dialog_id);
        }

        Ok(())
    }

    /// Send REFER for transfers
    pub async fn send_refer(
        &self,
        dialog_id: crate::types::DialogId,
        target: &str,
        attended: bool,
    ) -> Result<()> {
        // Convert our DialogId to RvoipDialogId
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();

        // Find session ID from dialog
        if let Some(entry) = self.dialog_to_session.get(&rvoip_dialog_id) {
            let session_id = entry.value().clone();
            drop(entry);

            // Send REFER through dialog API. Attended-transfer Replaces
            // belongs in `ReferRequestOptions.replaces` (an RFC 3891
            // header param on Refer-To), not as a REFER body — the
            // legacy code passed the literal "attended" string, which
            // had no on-wire effect. Attended transfers route through
            // `send_refer_with_options` paths that compute Replaces
            // from the held session's dialog identifiers.
            let _ = attended;
            self.dialog_api
                .send_refer_with_options(
                    &rvoip_dialog_id,
                    ReferRequestOptions {
                        refer_to: target.to_string(),
                        ..Default::default()
                    },
                )
                .await
                .map_err(|e| SessionError::DialogError(format!("Failed to send REFER: {}", e)))?;

            tracing::info!("Sent REFER to {} for session {}", target, session_id.0);
        } else {
            tracing::warn!("No session found for dialog {}", dialog_id);
        }

        Ok(())
    }

    /// Get remote URI for a dialog
    pub async fn get_remote_uri(&self, _dialog_id: crate::types::DialogId) -> Result<String> {
        // For now, return a placeholder
        Ok("sip:remote@example.com".to_string())
    }

    /// RFC 3261 §22.2 — resend an INVITE with `Authorization` (or
    /// `Proxy-Authorization`) header on the same dialog after the server
    /// challenged with 401/407. The `SendINVITEWithAuth` state-machine action
    /// owns auth header computation; this is a thin passthrough to dialog-core.
    ///
    /// Both REGISTER and INVITE 401/407 challenges flow through the state
    /// machine via `DialogToSessionEvent::AuthRequired` → `EventType::AuthRequired`;
    /// the previous inline REGISTER-auth shortcut (`handle_401_challenge`) was
    /// retired when INVITE auth landed. See `default.yaml`'s `Initiating` /
    /// `Registering` + `AuthRequired` transitions.
    #[allow(clippy::too_many_arguments)]
    pub async fn resend_invite_with_auth(
        &self,
        session_id: &SessionId,
        sdp: Option<String>,
        auth_header_name: &str,
        auth_header_value: String,
        extras: Vec<rvoip_sip_core::types::TypedHeader>,
        from_display: Option<String>,
        contact_override: Option<String>,
    ) -> Result<()> {
        // Fast-RTT race: an auth challenge can arrive while the original
        // `SendINVITE` action is still awaiting dialog-core's
        // `make_call_for_session`. The dialog exists in dialog-core, but the
        // session-core s2d map is inserted immediately after that await
        // returns. Poll briefly so the retry can reuse the just-created
        // dialog instead of failing spuriously with SessionNotFound.
        use tokio::time::{Duration, Instant};
        let start = Instant::now();
        let dialog_id = loop {
            if let Some(entry) = self.session_to_dialog.get(session_id) {
                break entry.value().clone();
            }
            if start.elapsed() >= Duration::from_secs(1) {
                return Err(SessionError::SessionNotFound(session_id.0.clone()));
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        };

        // SIP_API_DESIGN_2 §7.3 — the application extras vector flows
        // from `pending_invite_options.extra_headers` so the retry wire
        // form matches the initial send. The §5.4 policy and the §6.1
        // outbound-proxy Route already ran when the original snapshot
        // was staged; the extras are passed through verbatim.
        self.dialog_api
            .send_invite_with_auth(
                &dialog_id,
                sdp,
                auth_header_name,
                auth_header_value,
                extras,
                from_display,
                contact_override,
            )
            .await
            .map_err(|e| {
                SessionError::DialogError(format!(
                    "resend_invite_with_auth failed for session {}: {}",
                    session_id.0, e
                ))
            })?;
        Ok(())
    }

    /// RFC 4028 §6 — resend an INVITE with a bumped `Session-Expires` /
    /// `Min-SE` after a 422 Session Interval Too Small. The UAS's Min-SE
    /// floor is supplied by the caller (parsed from the 422 response by
    /// dialog-core). The timer headers bypass
    /// [`DialogManagerConfig`](rvoip_sip_dialog::config::DialogManagerConfig)'s
    /// global values and use these overrides verbatim.
    pub async fn resend_invite_with_session_timer_override(
        &self,
        session_id: &SessionId,
        sdp: Option<String>,
        session_secs: u32,
        min_se: u32,
    ) -> Result<()> {
        // Fast-RTT race: when the UAS answers 422 on a loopback socket the
        // response can be processed before the initial `make_call_for_session`
        // call has returned and inserted the s2d mapping (see
        // `send_invite_with_details` below — the insert happens after the
        // await). Poll briefly for the mapping to appear. Cap at 1s; a
        // timeout here propagates as `SessionNotFound` which the retry
        // action's error path converts into a terminal `CallFailed`.
        use tokio::time::{Duration, Instant};
        let start = Instant::now();
        let dialog_id = loop {
            if let Some(entry) = self.session_to_dialog.get(session_id) {
                break entry.value().clone();
            }
            if start.elapsed() >= Duration::from_secs(1) {
                return Err(SessionError::SessionNotFound(session_id.0.clone()));
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        };

        self.dialog_api
            .send_invite_with_session_timer_override(&dialog_id, sdp, session_secs, min_se)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!(
                    "resend_invite_with_session_timer_override failed for session {}: {}",
                    session_id.0, e
                ))
            })?;
        Ok(())
    }

    /// Does the remote peer support RFC 3262 100rel? Used to gate
    /// `send_early_media` — we only emit a reliable 183 when the caller
    /// advertised `Supported: 100rel` (or `Require: 100rel`) on the INVITE.
    /// Returns `SessionNotFound` if the session has no dialog yet.
    pub async fn peer_supports_100rel(&self, session_id: &SessionId) -> Result<bool> {
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .map(|e| e.value().clone())
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;

        let dialog = self
            .dialog_api
            .get_dialog_info(&dialog_id)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!(
                    "peer_supports_100rel: failed to read dialog {}: {}",
                    dialog_id, e
                ))
            })?;

        Ok(dialog.peer_supports_100rel)
    }

    // ===== Outbound Actions (from state machine) =====

    /// Send INVITE for UAC - this is the primary method for initiating calls
    ///
    /// This method:
    /// 1. Creates a dialog in dialog-core
    /// 2. Sends the INVITE request
    /// 3. Stores the session-to-dialog mapping
    ///
    /// # Arguments
    /// * `session_id` - The session ID from the state machine
    /// * `from` - The From URI (e.g., "sip:alice@example.com")
    /// * `to` - The To URI (e.g., "sip:bob@example.com")
    /// * `sdp` - Optional SDP offer
    pub async fn send_invite_with_details(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
    ) -> Result<()> {
        // Use make_call_with_id to control the Call-ID
        let call_id = format!("{}@rvoip-sip", session_id.0);

        // Store Call-ID mapping BEFORE making the call to avoid race condition
        // This ensures any events that come back immediately can find the session
        self.callid_to_session
            .insert(call_id.clone(), session_id.clone());

        // Use `make_call_for_session` so the session↔dialog mapping is
        // installed on dialog-core *before* the INVITE goes on the wire.
        // This closes the fast-RTT race where a 4xx response (e.g. 420 Bad
        // Extension on localhost) can be processed by the event loop before
        // the async `StoreDialogMapping` below has populated the lookup
        // tables — which would otherwise cause the CallFailed event to be
        // silently dropped by `event_hub::convert_coordination_to_cross_crate`.
        let call_handle = self
            .dialog_api
            .make_call_for_session(&session_id.0, from, to, sdp, Some(call_id.clone()))
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to make call: {}", e)))?;

        let dialog_id = call_handle.call_id().clone();

        // Store remaining mappings on session-core side
        self.session_to_dialog
            .insert(session_id.clone(), dialog_id.clone());
        self.dialog_to_session
            .insert(dialog_id.clone(), session_id.clone());

        // Publish StoreDialogMapping event to inform dialog-core about the session-dialog mapping
        let event = SessionToDialogEvent::StoreDialogMapping {
            session_id: session_id.0.clone(),
            dialog_id: dialog_id.to_string(),
        };
        self.global_coordinator
            .publish(Arc::new(RvoipCrossCrateEvent::SessionToDialog(event)))
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to publish StoreDialogMapping: {}", e))
            })?;

        tracing::info!(
            "Published StoreDialogMapping for session {} -> dialog {}",
            session_id.0,
            dialog_id
        );

        // Store the transaction ID for later ACK sending
        // Note: CallHandle might not expose transaction_id directly
        // For now, we'll rely on dialog-core to handle ACKs internally
        tracing::debug!(
            "Dialog {} created for session {} - ACK will be handled by dialog-core",
            dialog_id,
            session_id.0
        );

        // Don't update session store here - the state machine will handle updating the dialog ID
        tracing::debug!("Dialog {} created for session {}", dialog_id, session_id.0);

        Ok(())
    }

    /// Like [`send_invite_with_details`](Self::send_invite_with_details) but appends caller-supplied extra
    /// headers to the outgoing INVITE. Routes through dialog-core's
    /// `make_call_with_extra_headers_for_session` so the extras (typically
    /// `P-Asserted-Identity` per RFC 3325) ride on the very first wire
    /// transmission rather than being added in a follow-up.
    ///
    /// Used by the `SendINVITE` action when `SessionState.pai_uri` is set;
    /// the action handler builds the typed PAI header from the URI and
    /// passes it through here.
    pub async fn send_invite_with_extra_headers(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        self.send_invite_with_extra_headers_inner(
            session_id,
            from,
            to,
            sdp,
            extra_headers,
            true, // apply global outbound-proxy Route
        )
        .await
    }

    /// SIP_API_DESIGN_2 §6.1 — variant used by builder dispatch when
    /// the builder has set its own per-call `with_outbound_proxy(uri)`
    /// override (already prepended as a `Route:` in
    /// `Action::SendINVITEWithOptions`). Skips the global
    /// `Config.outbound_proxy_uri` so the wire doesn't end up with two
    /// stacked proxy Routes when the caller meant to override the
    /// default.
    pub async fn send_invite_with_extra_headers_no_global_proxy(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        self.send_invite_with_extra_headers_inner(session_id, from, to, sdp, extra_headers, false)
            .await
    }

    async fn send_invite_with_extra_headers_inner(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
        apply_global_proxy: bool,
    ) -> Result<()> {
        let call_id = format!("{}@rvoip-sip", session_id.0);

        self.callid_to_session
            .insert(call_id.clone(), session_id.clone());

        // E4 / RFC 3261 §8.1.2: when an outbound proxy is configured, pre-load
        // it as the first Route header on the INVITE so the request traverses
        // the proxy regardless of the Request-URI target. We preserve caller-
        // supplied extras (e.g. `P-Asserted-Identity` from B1) by prepending,
        // not replacing.
        let headers = if apply_global_proxy {
            prepend_outbound_proxy_route(extra_headers, self.outbound_proxy_uri.as_ref())
        } else {
            extra_headers
        };
        if apply_global_proxy && self.outbound_proxy_uri.is_some() {
            tracing::debug!(
                "E4 outbound proxy: prepended Route to INVITE for session {}",
                session_id.0
            );
        }

        let call_handle = self
            .dialog_api
            .make_call_with_extra_headers_for_session(
                &session_id.0,
                from,
                to,
                sdp,
                Some(call_id.clone()),
                headers,
            )
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to make call with extra headers: {}", e))
            })?;

        let dialog_id = call_handle.call_id().clone();

        self.session_to_dialog
            .insert(session_id.clone(), dialog_id.clone());
        self.dialog_to_session
            .insert(dialog_id.clone(), session_id.clone());

        let event = SessionToDialogEvent::StoreDialogMapping {
            session_id: session_id.0.clone(),
            dialog_id: dialog_id.to_string(),
        };
        self.global_coordinator
            .publish(Arc::new(RvoipCrossCrateEvent::SessionToDialog(event)))
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to publish StoreDialogMapping: {}", e))
            })?;

        tracing::info!(
            "send_invite_with_extra_headers: published StoreDialogMapping for session {} -> dialog {} ({} extra header(s))",
            session_id.0,
            dialog_id,
            self.session_to_dialog
                .get(session_id)
                .map(|_| "ok")
                .unwrap_or("missing"),
        );

        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase B — structured initial-INVITE dispatch. The
    /// rvoip-sip counterpart of dialog-core `send_invite_with_options`: carries
    /// the `From` display name and `Contact` as typed fields instead of
    /// smuggling them through `extra_headers`. `apply_global_proxy` follows the
    /// same rule as [`Self::send_invite_with_extra_headers`] — skip the global
    /// `Config.outbound_proxy_uri` Route when the builder set a per-call
    /// override (already a `Route:` in `opts.extra_headers`).
    pub async fn send_invite_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InviteRequestOptions,
        apply_global_proxy: bool,
    ) -> Result<()> {
        let call_id = format!("{}@rvoip-sip", session_id.0);
        self.callid_to_session
            .insert(call_id.clone(), session_id.clone());

        if apply_global_proxy {
            opts.extra_headers =
                prepend_outbound_proxy_route(opts.extra_headers, self.outbound_proxy_uri.as_ref());
            if self.outbound_proxy_uri.is_some() {
                tracing::debug!(
                    "E4 outbound proxy: prepended Route to INVITE for session {}",
                    session_id.0
                );
            }
        }
        opts.call_id = Some(call_id.clone());

        let call_handle = self
            .dialog_api
            .send_invite_with_options_for_session(&session_id.0, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send INVITE with options: {}", e))
            })?;

        let dialog_id = call_handle.call_id().clone();
        self.session_to_dialog
            .insert(session_id.clone(), dialog_id.clone());
        self.dialog_to_session
            .insert(dialog_id.clone(), session_id.clone());

        let event = SessionToDialogEvent::StoreDialogMapping {
            session_id: session_id.0.clone(),
            dialog_id: dialog_id.to_string(),
        };
        self.global_coordinator
            .publish(Arc::new(RvoipCrossCrateEvent::SessionToDialog(event)))
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to publish StoreDialogMapping: {}", e))
            })?;

        Ok(())
    }

    /// Send 200 OK response
    pub async fn send_200_ok(&self, session_id: &SessionId, sdp: Option<String>) -> Result<()> {
        self.send_response(session_id, 200, sdp).await
    }

    /// Send response with SDP
    pub async fn send_response_with_sdp(
        &self,
        session_id: &SessionId,
        code: u16,
        _reason: &str,
        sdp: &str,
    ) -> Result<()> {
        self.send_response(session_id, code, Some(sdp.to_string()))
            .await
    }

    /// Send response without SDP
    pub async fn send_response_session(
        &self,
        session_id: &SessionId,
        code: u16,
        _reason: &str,
    ) -> Result<()> {
        self.send_response(session_id, code, None).await
    }

    /// Send error response
    pub async fn send_error_response(
        &self,
        session_id: &SessionId,
        code: StatusCode,
        _reason: &str,
    ) -> Result<()> {
        self.send_response(session_id, code.as_u16(), None).await
    }

    /// SIP_API_DESIGN_2 Phase D — 3xx redirect dispatch with
    /// application-staged extras (e.g., a registrar's 305 Use Proxy
    /// with `Retry-After:`).
    pub async fn send_redirect_response_with_options(
        &self,
        session_id: &SessionId,
        status: u16,
        contacts: Vec<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        tracing::info!(
            "DialogAdapter sending {} redirect for session {} with {} contact(s), {} staged extras",
            status,
            session_id.0,
            contacts.len(),
            extra_headers.len()
        );
        self.dialog_api
            .send_redirect_response_with_extras_for_session(
                &session_id.0,
                status,
                contacts,
                extra_headers,
            )
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to send redirect (with extras) for session {}: {}",
                    session_id.0,
                    e
                );
                SessionError::DialogError(format!("Failed to send redirect: {}", e))
            })
    }

    /// Send a 3xx redirect response with one or more `Contact:` URIs
    /// (RFC 3261 §8.1.3.4). Thin wrapper over
    /// `UnifiedDialogApi::send_redirect_response_for_session`.
    pub async fn send_redirect_response(
        &self,
        session_id: &SessionId,
        status: u16,
        contacts: Vec<String>,
    ) -> Result<()> {
        tracing::info!(
            "DialogAdapter sending {} redirect for session {} with {} contact(s)",
            status,
            session_id.0,
            contacts.len()
        );
        self.dialog_api
            .send_redirect_response_for_session(&session_id.0, status, contacts)
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to send redirect for session {}: {}",
                    session_id.0,
                    e
                );
                SessionError::DialogError(format!("Failed to send redirect: {}", e))
            })
    }

    /// SIP_API_DESIGN_2 Phase D — UAS response dispatch that
    /// threads application-staged headers to the wire. The session's
    /// pending UAS transaction is resolved internally by
    /// `UnifiedDialogApi::send_response_with_extras_for_session`,
    /// which appends `extra_headers` *after* the stack-managed
    /// `From` / `To` / `Via` / `Call-ID` / `CSeq` / `Content-Length`
    /// / `Contact` / `Record-Route` are stamped.
    pub async fn send_response_with_options(
        &self,
        session_id: &SessionId,
        code: u16,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        tracing::info!(
            "DialogAdapter sending {} response for session {} with {} staged extras",
            code,
            session_id.0,
            extra_headers.len()
        );
        self.dialog_api
            .send_response_with_extras_for_session(&session_id.0, code, sdp, extra_headers)
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to send response (with extras) for session {}: {}",
                    session_id.0,
                    e
                );
                SessionError::DialogError(format!("Failed to send response: {}", e))
            })
    }

    /// Send response (for UAS)
    pub async fn send_response(
        &self,
        session_id: &SessionId,
        code: u16,
        sdp: Option<String>,
    ) -> Result<()> {
        tracing::info!(
            "DialogAdapter sending {} response for session {} with SDP: {}",
            code,
            session_id.0,
            sdp.is_some()
        );

        // Use dialog-core's session-based response method
        self.dialog_api
            .send_response_for_session(&session_id.0, code, sdp)
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to send response for session {}: {}",
                    session_id.0,
                    e
                );
                SessionError::DialogError(format!("Failed to send response: {}", e))
            })
    }

    /// Send a UAS response through a known inbound server transaction.
    pub async fn send_response_for_transaction(
        &self,
        session_id: &SessionId,
        transaction_id: &TransactionKey,
        code: u16,
        sdp: Option<String>,
    ) -> Result<()> {
        tracing::info!(
            "DialogAdapter sending {} response for session {} via transaction {} with SDP: {}",
            code,
            session_id.0,
            transaction_id,
            sdp.is_some()
        );

        self.dialog_api
            .send_response_for_session_transaction(&session_id.0, transaction_id, code, sdp)
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to send response for session {} via transaction {}: {}",
                    session_id.0,
                    transaction_id,
                    e
                );
                SessionError::DialogError(format!("Failed to send response: {}", e))
            })
    }

    /// Send ACK (for UAC after 200 OK)
    pub async fn send_ack(&self, session_id: &SessionId, response: &Response) -> Result<()> {
        // Get the dialog ID for this session
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();

        // Check if we have the original INVITE transaction ID stored
        if let Some(tx_id) = self.outgoing_invite_tx.get(session_id) {
            // Use the proper ACK method with transaction ID
            self.dialog_api
                .send_ack_for_2xx_response(&dialog_id, &tx_id, response)
                .await
                .map_err(|e| SessionError::DialogError(format!("Failed to send ACK: {}", e)))?;

            // Clean up the stored transaction ID after successful ACK
            self.outgoing_invite_tx.remove(session_id);
        } else {
            // Fallback: Try to send ACK without transaction ID (may not work properly)
            tracing::debug!(
                "No transaction ID stored for session {}, ACK may fail",
                session_id.0
            );
            // The dialog-core API doesn't have a direct send_ack without transaction ID
            // so we'll need to handle this case differently in production
        }

        Ok(())
    }

    /// Send BYE to terminate call (for state machine)
    pub async fn send_bye_session(&self, session_id: &SessionId) -> Result<()> {
        let dialog_id = {
            let entry = self
                .session_to_dialog
                .get(session_id)
                .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
            entry.value().clone()
        };

        self.dialog_api
            .send_bye_with_options(&dialog_id, ByeRequestOptions::default())
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send BYE: {}", e)))?;

        Ok(())
    }

    /// Send BYE with an RFC 3326 Reason header to terminate a call.
    pub async fn send_bye_session_with_reason(
        &self,
        session_id: &SessionId,
        reason: rvoip_sip_core::types::reason::Reason,
    ) -> Result<()> {
        let dialog_id = {
            let entry = self
                .session_to_dialog
                .get(session_id)
                .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
            entry.value().clone()
        };

        self.dialog_api
            .send_bye_with_options(
                &dialog_id,
                ByeRequestOptions {
                    reason: Some(reason.to_string()),
                    ..Default::default()
                },
            )
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send BYE with Reason: {}", e))
            })?;

        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — UPDATE (RFC 3311) dispatch routed
    /// through the new dialog-core options surface. SDP is optional;
    /// when present it rides on the UPDATE body. The builder layer
    /// supplies a fully-populated `UpdateRequestOptions`.
    pub async fn send_update_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::UpdateRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Update,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_update_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send UPDATE: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — re-INVITE dispatch routed through
    /// the new dialog-core options surface so applications can
    /// attach precomputed `Authorization:` or stage extra headers.
    pub async fn send_reinvite_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::ReInviteRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Invite,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_reinvite_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send re-INVITE: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — REFER dispatch through the new
    /// dialog-core options surface; carries the full RFC 3891
    /// `Replaces`, RFC 3892 `Referred-By`, RFC 4538 `Target-Dialog`
    /// trio.
    pub async fn send_refer_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::ReferRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Refer,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_refer_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send REFER: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — INFO dispatch through the new
    /// dialog-core options surface, replacing the legacy
    /// `send_info(content_type, body)` path.
    pub async fn send_info_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InfoRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Info,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_info_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send INFO: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — BYE dispatch through the new
    /// dialog-core options surface; carries the optional RFC 3326
    /// `Reason:` header.
    pub async fn send_bye_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::ByeRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Bye,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_bye_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send BYE: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — NOTIFY dispatch through the new
    /// dialog-core options surface.
    pub async fn send_notify_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::NotifyRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Notify,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_notify_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send NOTIFY: {}", e)))?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog MESSAGE dispatch
    /// through the new dialog-core options surface. Returns the
    /// registrar's `Response` so the caller can inspect 200 OK vs
    /// 401 auth-challenge vs 404. No session_id is required because
    /// MESSAGE is fire-and-forget per RFC 3428.
    pub async fn send_message_oob_with_options(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::MessageRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Message,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        self.dialog_api
            .send_message_out_of_dialog_with_options(opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send MESSAGE: {}", e)))
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog OPTIONS dispatch.
    /// Today returns the wire-`Response` when dialog-core ships the
    /// transaction-authorship; until then dialog-core's stub returns
    /// `NotImplemented` and that error bubbles through unchanged.
    pub async fn send_options_oob_with_options(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::OptionsRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Options,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        self.dialog_api
            .send_options_out_of_dialog_with_options(opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send OPTIONS: {}", e)))
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog SUBSCRIBE dispatch.
    /// Returns the registrar's `Response` so callers can inspect
    /// `Expires`, `Min-Expires`, or 401 challenge.
    pub async fn send_subscribe_oob_with_options(
        &self,
        target: &str,
        mut opts: rvoip_sip_dialog::api::unified::SubscribeRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Subscribe,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        self.dialog_api
            .send_subscribe_with_options(target, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send SUBSCRIBE: {}", e)))
    }

    // ─────────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 R2 — auth-retry mirrors for non-INVITE/non-REGISTER
    // methods. Each `send_<method>_with_auth` takes the same options
    // struct as its non-auth sibling plus a pre-computed `Authorization:`
    // (or `Proxy-Authorization:`) header, validates the application
    // extras via `apply_outbound_extras_policy_with_auth`, then injects
    // the stack-computed auth header at the end before handing off to
    // dialog-core. Called by `Action::SendRequestWithAuth` after the
    // matching client auth scheme computes the response for the cached
    // challenge.
    // ─────────────────────────────────────────────────────────────────────

    pub async fn send_bye_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::ByeRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Bye,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_bye_with_options(&dialog_id, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send BYE with auth: {}", e))
            })?;
        Ok(())
    }

    pub async fn send_refer_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::ReferRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Refer,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_refer_with_options(&dialog_id, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send REFER with auth: {}", e))
            })?;
        Ok(())
    }

    pub async fn send_notify_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::NotifyRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Notify,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_notify_with_options(&dialog_id, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send NOTIFY with auth: {}", e))
            })?;
        Ok(())
    }

    pub async fn send_info_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InfoRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Info,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_info_with_options(&dialog_id, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send INFO with auth: {}", e))
            })?;
        Ok(())
    }

    pub async fn send_update_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::UpdateRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Update,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();
        self.dialog_api
            .send_update_with_options(&dialog_id, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send UPDATE with auth: {}", e))
            })?;
        Ok(())
    }

    pub async fn send_message_oob_with_auth(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::MessageRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Message,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        self.dialog_api
            .send_message_out_of_dialog_with_options(opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send MESSAGE with auth: {}", e))
            })
    }

    pub async fn send_options_oob_with_auth(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::OptionsRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Options,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        self.dialog_api
            .send_options_out_of_dialog_with_options(opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send OPTIONS with auth: {}", e))
            })
    }

    pub async fn send_subscribe_oob_with_auth(
        &self,
        target: &str,
        mut opts: rvoip_sip_dialog::api::unified::SubscribeRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Subscribe,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        self.dialog_api
            .send_subscribe_with_options(target, opts)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send SUBSCRIBE with auth: {}", e))
            })
    }

    /// Send CANCEL to cancel pending INVITE
    pub async fn send_cancel(&self, session_id: &SessionId) -> Result<()> {
        let dialog_id = {
            let entry = self
                .session_to_dialog
                .get(session_id)
                .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
            entry.value().clone()
        };

        self.dialog_api
            .send_cancel_with_options(&dialog_id, CancelRequestOptions::default())
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send CANCEL: {}", e)))?;

        Ok(())
    }

    /// SIP_API_DESIGN_2 Phase C — CANCEL dispatch through the new
    /// dialog-core options surface. Carries the optional RFC 3326
    /// `Reason:` and any application-staged extras to the wire.
    /// SIP_API_DESIGN_2 §7.1 — REGISTER dispatch through the new
    /// dialog-core options surface with policy validation and outbound-
    /// proxy route prepended. Used by `Action::SendREGISTERWithOptions`
    /// for the unified builder path; the legacy `send_register` path
    /// stays separate because its extras vector is empty and the route
    /// goes through `outbound_proxy_uri` directly on the options struct.
    pub async fn send_register_with_options(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::RegisterRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Register,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        self.dialog_api
            .send_register_with_options(opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send REGISTER: {}", e)))
    }

    pub async fn send_cancel_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::CancelRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Cancel,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = {
            let entry = self
                .session_to_dialog
                .get(session_id)
                .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
            entry.value().clone()
        };

        self.dialog_api
            .send_cancel_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send CANCEL: {}", e)))?;

        Ok(())
    }

    /// Send an in-dialog INFO request (RFC 6086) with a caller-chosen
    /// `Content-Type`. Used for SIP-INFO DTMF (`application/dtmf-relay`),
    /// fax flow control (`application/sipfrag`), and other application-level
    /// mid-dialog signalling.
    pub async fn send_info(
        &self,
        session_id: &SessionId,
        content_type: &str,
        body: &[u8],
    ) -> Result<()> {
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();

        self.dialog_api
            .send_info_with_options(
                &dialog_id,
                InfoRequestOptions {
                    content_type: content_type.to_string(),
                    body: bytes::Bytes::copy_from_slice(body),
                    ..Default::default()
                },
            )
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send INFO: {}", e)))?;

        tracing::debug!(
            session = %session_id.0,
            content_type = %content_type,
            body_len = body.len(),
            "Sent INFO"
        );
        Ok(())
    }

    /// Send REFER for blind transfer (for state machine)
    pub async fn send_refer_session(&self, session_id: &SessionId, refer_to: &str) -> Result<()> {
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();

        // Send REFER through dialog API
        self.dialog_api
            .send_refer_with_options(
                &dialog_id,
                ReferRequestOptions {
                    refer_to: refer_to.to_string(),
                    ..Default::default()
                },
            )
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send REFER: {}", e)))?;

        tracing::info!("Sent REFER to {} for session {}", refer_to, session_id.0);
        Ok(())
    }

    /// Fetch the SIP-level dialog identity (`Call-ID`, `local_tag`, `remote_tag`)
    /// for a session. Returns `None` if the session has no dialog yet
    /// (e.g., the INVITE hasn't been sent) or the dialog was lost.
    ///
    /// Callers use this to construct a Replaces header value when driving
    /// attended transfer from a higher layer.
    pub async fn dialog_identity(&self, session_id: &SessionId) -> Result<Option<DialogIdentity>> {
        let dialog_id = match self.session_to_dialog.get(session_id) {
            Some(entry) => entry.clone(),
            None => return Ok(None),
        };

        let dialog = match self.dialog_api.get_dialog_info(&dialog_id).await {
            Ok(d) => d,
            Err(_) => return Ok(None),
        };

        Ok(Some(DialogIdentity {
            call_id: dialog.call_id,
            local_tag: dialog.local_tag,
            remote_tag: dialog.remote_tag,
        }))
    }

    /// Send a re-INVITE for hold/resume or mid-call SDP updates.
    ///
    /// RFC 3261 §14 — re-INVITE is the standard mechanism for modifying an
    /// established dialog's session parameters (SDP direction attributes for
    /// hold/resume, codec changes, etc.). This previously routed through
    /// UPDATE (RFC 3311) which caused Timer F timeouts when the remote
    /// didn't answer an UPDATE promptly; re-INVITE is both more widely
    /// supported and the RFC-recommended method here.
    pub async fn send_reinvite_session(&self, session_id: &SessionId, sdp: String) -> Result<()> {
        use rvoip_sip_core::Method;

        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?
            .clone();

        self.dialog_api
            .send_request_in_dialog(&dialog_id, Method::Invite, Some(bytes::Bytes::from(sdp)))
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send re-INVITE: {}", e)))?;

        Ok(())
    }

    /// Clean up all mappings and resources for a session
    pub async fn cleanup_session(&self, session_id: &SessionId) -> Result<()> {
        let guard = cleanup_diag::stage_guard(CleanupStage::DialogCleanup, &session_id.0);
        self.cleanup_attempt_total.fetch_add(1, Ordering::Relaxed);
        // Remove from all mappings
        if let Some(dialog_id) = self.session_to_dialog.remove(session_id) {
            self.cleanup_mapped_total.fetch_add(1, Ordering::Relaxed);
            self.dialog_to_session.remove(&dialog_id.1);
            self.dialog_api
                .dialog_manager()
                .core()
                .cleanup_dialog_storage_and_transactions(&dialog_id.1)
                .await;
        } else {
            self.cleanup_missing_total.fetch_add(1, Ordering::Relaxed);
        }

        let call_ids_to_remove: Vec<_> = self
            .callid_to_session
            .iter()
            .filter(|entry| entry.value() == session_id)
            .map(|entry| entry.key().clone())
            .collect();
        for call_id in call_ids_to_remove {
            self.callid_to_session.remove(&call_id);
            self.cleanup_call_ids_removed_total
                .fetch_add(1, Ordering::Relaxed);
        }

        if self.outgoing_invite_tx.remove(session_id).is_some() {
            self.cleanup_outgoing_invite_removed_total
                .fetch_add(1, Ordering::Relaxed);
        }

        tracing::debug!(
            "Cleaned up dialog adapter mappings for session {}",
            session_id.0
        );
        guard.finish_success();
        Ok(())
    }

    // ===== Registration Methods =====

    async fn start_symmetric_registration_keepalive(&self, from_uri: &str, registrar_uri: &str) {
        let Some(params) = self.symmetric_flow_params.as_ref() else {
            return;
        };

        let dest_uri = match registrar_uri.parse::<rvoip_sip_core::Uri>() {
            Ok(uri) => uri,
            Err(e) => {
                tracing::warn!(
                    "symmetric registered-flow: invalid registrar URI {}: {}",
                    registrar_uri,
                    e
                );
                return;
            }
        };
        let Some(destination) =
            rvoip_sip_dialog::dialog::dialog_utils::resolve_uri_to_socketaddr(&dest_uri).await
        else {
            tracing::warn!(
                "symmetric registered-flow: could not resolve registrar URI {} for keep-alive",
                registrar_uri
            );
            return;
        };

        self.dialog_api.dialog_manager().core().start_outbound_ping(
            (
                from_uri.to_string(),
                params.reg_id,
                params.instance_urn.clone(),
            ),
            destination,
        );
        tracing::info!(
            "symmetric registered-flow: keep-alive ping started for AoR {} (reg-id={}, instance={}) → {}",
            from_uri,
            params.reg_id,
            params.instance_urn,
            destination
        );
    }

    /// Send REGISTER request and process response.
    ///
    /// `extras` carry application-staged additional headers (e.g. from
    /// `coord.register(..).with_header(..)`); they ride alongside the
    /// stack-managed headers per SIP_API_DESIGN_2.md §7.3. On auth retry
    /// the caller passes the same extras snapshot so headers survive the
    /// 401/407 hop.
    pub(crate) async fn send_register(
        &self,
        session_id: &SessionId,
        registrar_uri: &str,
        from_uri: &str,
        contact_uri: &str,
        expires: u32,
        auth: Option<&crate::auth::SipClientAuth>,
        extras: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<RegisterAttemptOutcome> {
        tracing::info!(
            "Sending REGISTER for session {} to {} (expires={})",
            session_id.0,
            registrar_uri,
            expires
        );

        // Build authorization header if auth material provided.
        let (authorization, proxy_authorization) = if let Some(auth) = auth {
            // Get challenge from session
            let mut session = self.store.get_session(session_id).await?;
            if let Some(challenge_raw) = session.auth_challenge_raw.clone().or_else(|| {
                session.auth_challenge.as_ref().map(|challenge| {
                    rvoip_auth_core::DigestAuthenticator::new(challenge.realm.clone())
                        .format_www_authenticate(challenge)
                })
            }) {
                // RFC 7616 §3.4.5 — bump the per-(realm, nonce) NC
                // counter before computing. REGISTER reuses one nonce
                // across many refreshes, so this is exactly the path
                // where carriers reject `nc=00000001` repeats.
                let digest_challenge = session.auth_challenge.clone().or_else(|| {
                    rvoip_auth_core::DigestAuthenticator::parse_challenge(&challenge_raw).ok()
                });
                let nc_value = if let Some(challenge) = digest_challenge.as_ref() {
                    let nc_key = (challenge.realm.clone(), challenge.nonce.clone());
                    *session
                        .digest_nc
                        .entry(nc_key)
                        .and_modify(|n| *n += 1)
                        .or_insert(1)
                } else {
                    1
                };
                let transport_context = session
                    .pending_auth_transport
                    .clone()
                    .unwrap_or_else(|| self.outbound_transport_context_for_uri(registrar_uri));
                session.pending_auth_transport = None;
                self.store.update_session(session.clone()).await?;

                tracing::info!(
                    "🔍 CLIENT: Computing auth for REGISTER uri={}, nc={}",
                    registrar_uri,
                    nc_value
                );

                // REGISTER body is empty; pass `None` so the qop
                // selector picks `auth` (or legacy if no qop offered)
                // rather than `auth-int`.
                let selected = auth.authorization_for_challenge_with_transport_context(
                    &challenge_raw,
                    "REGISTER",
                    registrar_uri,
                    nc_value,
                    None,
                    &transport_context,
                )?;

                tracing::info!(
                    "🔍 CLIENT: Computed REGISTER auth using {:?}",
                    selected.scheme
                );

                let status = session
                    .pending_auth
                    .as_ref()
                    .map(|(status, _)| *status)
                    .unwrap_or(401);
                if status == 407 {
                    (None, Some(selected.value))
                } else {
                    (Some(selected.value), None)
                }
            } else {
                tracing::debug!("No challenge stored, sending without auth");
                (None, None)
            }
        } else {
            (None, None)
        };

        // RFC 3581 NAT discovery: if the dialog manager has learned a
        // public address from a prior response's `Via:
        // …;received=…;rport=…`, rewrite the host:port portion of the
        // Contact URI so the registrar binds the new registration to
        // the externally-routable address (RFC 5626 §5). First
        // REGISTER goes out with the bind-address Contact; the
        // response carries `received=`/`rport=` which populates the
        // discovery cache; subsequent REGISTERs (refresh, auth retry)
        // use the discovered address.
        let rewritten_contact = if let Some(public) = self.dialog_api.discovered_public_addr().await
        {
            let rewritten = rewrite_contact_host(contact_uri, public);
            if rewritten != contact_uri {
                tracing::info!(
                    "RFC 3581/5626: rewriting REGISTER Contact {} → {} (NAT-discovered)",
                    contact_uri,
                    rewritten
                );
            }
            rewritten
        } else {
            contact_uri.to_string()
        };

        // Reserve registration identity for this new logical REGISTER
        // transaction. This is registration-scoped only; dialog-core still owns
        // all in-dialog CSeq state and transaction-layer retransmissions reuse
        // the request created below.
        let (registration_call_id, registration_cseq) = {
            let mut session = self.store.get_session(session_id).await?;
            let call_id = session
                .registration_call_id
                .get_or_insert_with(|| format!("reg-{}", uuid::Uuid::new_v4()))
                .clone();
            session.registration_cseq = session.registration_cseq.saturating_add(1);
            let cseq = session.registration_cseq;
            self.store.update_session(session).await?;
            (call_id, cseq)
        };

        // Send REGISTER through dialog-core API and get response.
        // A5 Phase 2a: when the coordinator is configured for RFC 5626 SIP
        // Outbound, route through the outbound-aware REGISTER so the Contact
        // carries `+sip.instance` + `reg-id` + `;ob`.
        let response = self
            .dialog_api
            .send_register_with_options(rvoip_sip_dialog::api::unified::RegisterRequestOptions {
                registrar_uri: registrar_uri.to_string(),
                aor_uri: from_uri.to_string(),
                contact_uri: rewritten_contact,
                expires,
                authorization,
                proxy_authorization,
                call_id: Some(registration_call_id),
                cseq: Some(registration_cseq),
                outbound_contact: self.outbound_contact_params.clone(),
                outbound_proxy_uri: self.outbound_proxy_uri.clone(),
                extra_headers: extras,
                refresh: false,
            })
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send REGISTER: {}", e)))?;

        tracing::info!(
            "REGISTER response received: {} for session {}",
            response.status_code(),
            session_id.0
        );

        let register_transport = self
            .dialog_api
            .outbound_transport_context_for_response(&response)
            .map(|context| {
                crate::auth::SipTransportSecurityContext::from_transport_context(&context)
            });
        if let Ok(mut session) = self.store.get_session(session_id).await {
            session.pending_auth_transport = register_transport;
            self.store.update_session(session).await?;
        }

        match response.status_code() {
            200..=299 => {
                let is_unregister = expires == 0;
                if is_unregister {
                    Ok(RegisterAttemptOutcome::Unregistered)
                } else {
                    let accepted_expires =
                        Self::accepted_registration_expires(&response, contact_uri, expires);
                    let metadata = Self::response_registration_metadata(&response);
                    Ok(RegisterAttemptOutcome::Registered {
                        accepted_expires,
                        metadata,
                    })
                }
            }
            401 | 407 => {
                // RFC 3261 §22.2 — auth challenge on REGISTER. The adapter
                // only extracts the challenge; the state-machine action owns
                // retry limits and the follow-up `AuthRequired` event.
                use rvoip_sip_core::types::headers::HeaderAccess;
                let header_name = if response.status_code() == 407 {
                    rvoip_sip_core::types::header::HeaderName::ProxyAuthenticate
                } else {
                    rvoip_sip_core::types::header::HeaderName::WwwAuthenticate
                };
                let challenges = response
                    .raw_headers(&header_name)
                    .into_iter()
                    .filter_map(|bytes| String::from_utf8(bytes).ok())
                    .collect::<Vec<_>>();
                if !challenges.is_empty() {
                    Ok(RegisterAttemptOutcome::AuthChallenge {
                        status_code: response.status_code(),
                        challenge: challenges.join(", "),
                    })
                } else {
                    tracing::warn!(
                        "REGISTER {} without challenge header",
                        response.status_code()
                    );
                    Ok(RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "REGISTER challenge response did not include challenge header"
                            .to_string(),
                    })
                }
            }
            423 => {
                // RFC 3261 §10.2.8 — Interval Too Brief. The registrar requires
                // a minimum expiry; it MUST include a Min-Expires header with
                // its minimum acceptable value. The action owns the bounded
                // retry and re-enters this method iteratively.
                use rvoip_sip_core::types::headers::HeaderAccess;
                let min_expires = response
                    .raw_header_value(&rvoip_sip_core::types::header::HeaderName::MinExpires)
                    .and_then(|s| s.trim().parse::<u32>().ok());

                match min_expires {
                    Some(min_expires) if min_expires > 0 && min_expires <= 7200 => {
                        Ok(RegisterAttemptOutcome::IntervalTooBrief { min_expires })
                    }
                    Some(min_expires) => Ok(RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: format!(
                            "423 Interval Too Brief included invalid Min-Expires={}",
                            min_expires
                        ),
                    }),
                    None => Ok(RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "423 Interval Too Brief without Min-Expires header".to_string(),
                    }),
                }
            }
            _ => {
                tracing::warn!(
                    "❌ Registration failed with status {}",
                    response.status_code()
                );
                Ok(RegisterAttemptOutcome::Failure {
                    status_code: response.status_code(),
                    reason: response.reason_phrase().to_string(),
                })
            }
        }
    }

    pub async fn send_subscribe(
        &self,
        session_id: &SessionId,
        from_uri: &str,
        to_uri: &str,
        event_package: &str,
        expires: u32,
    ) -> Result<()> {
        tracing::info!(
            "Sending SUBSCRIBE for session {} from {} to {} for event {}",
            session_id.0,
            from_uri,
            to_uri,
            event_package
        );

        // Send as non-dialog request (creates dialog on 2xx). dialog-core
        // owns the wire-ready SIP request construction.
        let response = self
            .dialog_api
            .send_subscribe_with_options(
                to_uri,
                SubscribeRequestOptions {
                    event: event_package.to_string(),
                    expires,
                    from_uri: Some(from_uri.to_string()),
                    contact_uri: Some(from_uri.to_string()),
                    ..Default::default()
                },
            )
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send SUBSCRIBE: {}", e)))?;

        tracing::info!(
            "SUBSCRIBE response: {} for session {}",
            response.status_code(),
            session_id.0
        );

        // Handle response and potentially store dialog ID
        if response.status_code() == 200 || response.status_code() == 202 {
            // Extract dialog ID from response if present
            // This would normally come from the response headers
            // For now, emit subscription accepted event
            let event = RvoipCrossCrateEvent::DialogToSession(
                rvoip_infra_common::events::cross_crate::DialogToSessionEvent::SubscriptionAccepted {
                    session_id: session_id.0.clone(),
                }
            );
            let _ = self.global_coordinator.publish(Arc::new(event)).await;
        } else if response.status_code() >= 400 {
            let event = RvoipCrossCrateEvent::DialogToSession(
                rvoip_infra_common::events::cross_crate::DialogToSessionEvent::SubscriptionFailed {
                    session_id: session_id.0.clone(),
                    status_code: response.status_code(),
                },
            );
            let _ = self.global_coordinator.publish(Arc::new(event)).await;
        }

        Ok(())
    }

    /// Send a NOTIFY request within a subscription dialog
    pub async fn send_notify(
        &self,
        session_id: &SessionId,
        event_package: &str,
        body: Option<String>,
        subscription_state: Option<String>,
    ) -> Result<()> {
        tracing::info!(
            "Sending NOTIFY for session {} with event {} and state {:?}",
            session_id.0,
            event_package,
            subscription_state
        );

        // Get dialog ID for this session
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::DialogError("No dialog for session".to_string()))?
            .clone();

        // Send NOTIFY within the dialog
        self.dialog_api
            .send_notify_with_options(
                &dialog_id,
                NotifyRequestOptions {
                    event: event_package.to_string(),
                    subscription_state: subscription_state.unwrap_or_default(),
                    body: body.map(bytes::Bytes::from),
                    ..Default::default()
                },
            )
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send NOTIFY: {}", e)))?;

        tracing::info!("NOTIFY sent successfully for session {}", session_id.0);
        Ok(())
    }

    /// Send NOTIFY for REFER implicit subscription (RFC 3515)
    ///
    /// Convenience method that automatically formats NOTIFY for transfer progress
    pub async fn send_refer_notify(
        &self,
        session_id: &SessionId,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        tracing::info!(
            "Sending REFER NOTIFY for session {} with status {} {}",
            session_id.0,
            status_code,
            reason
        );

        // Get dialog ID for this session
        let dialog_id = self
            .session_to_dialog
            .get(session_id)
            .ok_or_else(|| SessionError::DialogError("No dialog for session".to_string()))?
            .clone();

        // Send REFER NOTIFY using dialog-core convenience method
        self.dialog_api
            .send_refer_notify(&dialog_id, status_code, reason)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!("Failed to send REFER NOTIFY: {}", e))
            })?;

        tracing::info!(
            "REFER NOTIFY sent successfully for session {}",
            session_id.0
        );
        Ok(())
    }

    // ===== MESSAGE Methods =====

    /// Send a MESSAGE request (can be in-dialog or out-of-dialog)
    pub async fn send_message(
        &self,
        session_id: &SessionId,
        from_uri: &str,
        to_uri: &str,
        body: String,
        in_dialog: bool,
    ) -> Result<()> {
        tracing::info!(
            "Sending MESSAGE for session {} from {} to {} (in_dialog: {})",
            session_id.0,
            from_uri,
            to_uri,
            in_dialog
        );

        if in_dialog {
            // Send MESSAGE within existing dialog
            let dialog_id = self
                .session_to_dialog
                .get(session_id)
                .ok_or_else(|| SessionError::DialogError("No dialog for session".to_string()))?
                .clone();

            self.dialog_api
                .send_request_in_dialog(
                    &dialog_id,
                    rvoip_sip_core::Method::Message,
                    Some(bytes::Bytes::from(body)),
                )
                .await
                .map_err(|e| {
                    SessionError::DialogError(format!("Failed to send MESSAGE in dialog: {}", e))
                })?;
        } else {
            // Send MESSAGE as standalone (no dialog). dialog-core owns the
            // wire-ready SIP request construction.
            let response = self
                .dialog_api
                .send_message_out_of_dialog_with_options(MessageRequestOptions {
                    from_uri: from_uri.to_string(),
                    to_uri: to_uri.to_string(),
                    content_type: String::from("text/plain"),
                    body: bytes::Bytes::from(body),
                    ..Default::default()
                })
                .await
                .map_err(|e| SessionError::DialogError(format!("Failed to send MESSAGE: {}", e)))?;

            // Handle response
            if response.status_code() == 200 {
                let event = RvoipCrossCrateEvent::DialogToSession(
                    rvoip_infra_common::events::cross_crate::DialogToSessionEvent::MessageDelivered {
                        session_id: session_id.0.clone(),
                    }
                );
                let _ = self.global_coordinator.publish(Arc::new(event)).await;
            } else if response.status_code() >= 400 {
                let event = RvoipCrossCrateEvent::DialogToSession(
                    rvoip_infra_common::events::cross_crate::DialogToSessionEvent::MessageFailed {
                        session_id: session_id.0.clone(),
                        status_code: response.status_code(),
                    },
                );
                let _ = self.global_coordinator.publish(Arc::new(event)).await;
            }
        }

        tracing::info!("MESSAGE sent successfully for session {}", session_id.0);
        Ok(())
    }

    // ===== Helper Methods =====

    // ===== Inbound Events (from dialog-core) =====

    /// Start the dialog API (no event handling here)
    pub async fn start(&self) -> Result<()> {
        // Start the dialog API
        self.dialog_api
            .start()
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to start dialog API: {}", e)))?;

        Ok(())
    }

    /// Stop the dialog API and release its transaction transports.
    pub async fn stop(&self) -> Result<()> {
        self.dialog_api
            .stop()
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to stop dialog API: {}", e)))?;

        Ok(())
    }
}

impl Clone for DialogAdapter {
    fn clone(&self) -> Self {
        Self {
            dialog_api: self.dialog_api.clone(),
            store: self.store.clone(),
            session_to_dialog: self.session_to_dialog.clone(),
            dialog_to_session: self.dialog_to_session.clone(),
            callid_to_session: self.callid_to_session.clone(),
            outgoing_invite_tx: self.outgoing_invite_tx.clone(),
            auto_emit_extra_headers: self.auto_emit_extra_headers.clone(),
            global_coordinator: self.global_coordinator.clone(),
            state_machine: self.state_machine.clone(),
            outbound_proxy_uri: self.outbound_proxy_uri.clone(),
            outbound_contact_params: self.outbound_contact_params.clone(),
            symmetric_flow_params: self.symmetric_flow_params.clone(),
            registration_auto_refresh: self.registration_auto_refresh,
            registration_refresh_jitter_percent: self.registration_refresh_jitter_percent,
            registration_refresh_tasks: self.registration_refresh_tasks.clone(),
            cleanup_attempt_total: self.cleanup_attempt_total.clone(),
            cleanup_mapped_total: self.cleanup_mapped_total.clone(),
            cleanup_missing_total: self.cleanup_missing_total.clone(),
            cleanup_call_ids_removed_total: self.cleanup_call_ids_removed_total.clone(),
            cleanup_outgoing_invite_removed_total: self
                .cleanup_outgoing_invite_removed_total
                .clone(),
            trace_redactor: self.trace_redactor.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- NAT-aware Contact rewrite (Sprint 1.A3) -------------------

    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    fn pub_addr() -> SocketAddr {
        SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)), 54321)
    }

    #[test]
    fn rewrite_contact_swaps_host_port_after_user() {
        // Standard `sip:user@host:port` form — host:port replaced.
        let input = "sip:alice@192.168.1.10:5060";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_preserves_uri_params() {
        let input = "sip:alice@192.168.1.10:5060;transport=tcp";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321;transport=tcp"
        );
    }

    #[test]
    fn rewrite_contact_handles_no_port_in_input() {
        let input = "sip:alice@192.168.1.10";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_handles_no_user() {
        // Some Contacts omit the user-part — rewrite host:port anyway.
        let input = "sip:192.168.1.10:5060";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_passes_through_sips_scheme() {
        let input = "sips:alice@192.168.1.10:5061;transport=tls";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sips:alice@203.0.113.7:54321;transport=tls"
        );
    }

    // ---- E4 outbound proxy pre-loaded Route ---------------------------

    use rvoip_sip_core::types::{uri::Uri, TypedHeader};
    use std::str::FromStr;

    #[test]
    fn prepend_outbound_proxy_route_with_proxy_adds_first_route() {
        let proxy = Uri::from_str("sip:sbc.example.com;lr").unwrap();
        let headers = prepend_outbound_proxy_route(Vec::new(), Some(&proxy));
        assert_eq!(headers.len(), 1);
        match &headers[0] {
            TypedHeader::Route(route) => {
                assert_eq!(route.len(), 1);
                assert_eq!(route[0].0.uri.to_string(), "sip:sbc.example.com;lr");
            }
            other => panic!("expected TypedHeader::Route, got {:?}", other),
        }
    }

    #[test]
    fn prepend_outbound_proxy_route_without_proxy_is_identity() {
        let pai_uri = Uri::from_str("sip:alice@pai.example.com").unwrap();
        let existing = vec![TypedHeader::PAssertedIdentity(
            rvoip_sip_core::types::p_asserted_identity::PAssertedIdentity::with_uri(pai_uri),
        )];
        let headers = prepend_outbound_proxy_route(existing.clone(), None);
        assert_eq!(headers.len(), existing.len());
        assert!(matches!(headers[0], TypedHeader::PAssertedIdentity(_)));
    }

    #[test]
    fn prepend_outbound_proxy_route_preserves_existing_before_route() {
        // Route goes FIRST, caller extras preserved after.
        let proxy = Uri::from_str("sip:sbc.example.com;lr").unwrap();
        let pai_uri = Uri::from_str("sip:alice@pai.example.com").unwrap();
        let existing = vec![TypedHeader::PAssertedIdentity(
            rvoip_sip_core::types::p_asserted_identity::PAssertedIdentity::with_uri(pai_uri),
        )];
        let headers = prepend_outbound_proxy_route(existing, Some(&proxy));
        assert_eq!(headers.len(), 2);
        assert!(matches!(headers[0], TypedHeader::Route(_)));
        assert!(matches!(headers[1], TypedHeader::PAssertedIdentity(_)));
    }
}

/// Rewrite the host (and port) portion of a SIP URI in a `Contact:`
/// value with the supplied public address. Preserves the scheme,
/// user-part (if any), and any URI parameters.
///
/// Used by `DialogAdapter::send_register` to redirect the registrar's
/// stored binding to the NAT-discovered public address (RFC 5626 §5).
/// Pure / sync so the rewrite is trivially testable without standing
/// up the full adapter.
///
/// Format we handle: `<scheme>:[<user>@]<host>[:<port>][;<params>]`.
/// We deliberately don't lean on a full URI parser here — the input
/// is always a Contact value we built ourselves earlier in the
/// pipeline, so the structure is predictable.
pub(crate) fn rewrite_contact_host(input: &str, public: std::net::SocketAddr) -> String {
    // Split off any URI params (`;name=value` after the host[:port]).
    let (host_section, params_suffix) = match input.find(';') {
        Some(idx) => (&input[..idx], &input[idx..]),
        None => (input, ""),
    };

    // Split scheme: prefix (`sip:` or `sips:`).
    let (scheme_prefix, after_scheme) = match host_section.find(':') {
        Some(idx) => (&host_section[..=idx], &host_section[idx + 1..]),
        None => return input.to_string(), // No `:` — not a SIP URI we recognise.
    };

    // Split optional `<user>@`.
    let (user_at, _existing_host_port) = match after_scheme.find('@') {
        Some(idx) => (&after_scheme[..=idx], &after_scheme[idx + 1..]),
        None => ("", after_scheme),
    };

    format!("{}{}{}{}", scheme_prefix, user_at, public, params_suffix)
}

/// SBC topology hiding (RFC 3261 §16-style) — strip every `Via:`
/// header below the topmost one.
///
/// Used when an SBC or stateless proxy mutates an inbound request
/// in-place before forwarding it, and wants to hide upstream hop
/// identities from the downstream peer. The top Via is preserved so
/// that the response can route back to *some* sender (typically the
/// SBC itself after it re-stamps the top Via with its own sent-by).
///
/// **NOT used by the B2BUA pattern in this codebase** — the standard
/// `coord.invite(...)` path builds a fresh outbound Request with the
/// SBC's own Via stamped fresh, so there's nothing to strip. This
/// helper is meaningful for proxy-style flows on top of
/// `Transport::send_message_raw` (i.e. the helpers planned for Phase
/// 8.5 stateless-proxy support).
///
/// Returns the number of Via headers removed (0 if there was only
/// one to begin with — common for endpoints that talk directly to
/// the SBC without intermediate proxies).
pub fn strip_via_below_top(request: &mut rvoip_sip_core::Request) -> usize {
    use rvoip_sip_core::types::TypedHeader;
    let mut seen_first_via = false;
    let mut removed = 0;
    request.headers.retain(|h| {
        if matches!(h, TypedHeader::Via(_)) {
            if seen_first_via {
                removed += 1;
                false
            } else {
                seen_first_via = true;
                true
            }
        } else {
            true
        }
    });
    removed
}

/// SBC topology hiding — strip every `Record-Route:` header whose
/// host does NOT match the supplied `self_host` (the SBC's own
/// public-facing host).
///
/// RFC 3261 §16.6 requires proxies to insert their own Record-Route
/// before forwarding so subsequent in-dialog requests come back
/// through them. An SBC doing topology hiding wants downstream to
/// see ONLY the SBC's own entry, not the upstream proxies that
/// previously inserted theirs.
///
/// `self_host` is matched against `Address.uri.host` as a case-
/// insensitive string. Pass the SBC's externally-visible host (e.g.
/// `"sbc.example.com"` or `"203.0.113.5"`) — typically what's also
/// used in `rewrite_contact_host`.
///
/// Returns the number of Record-Route entries (across all headers)
/// removed.
pub fn strip_record_route_below_self(
    request: &mut rvoip_sip_core::Request,
    self_host: &str,
) -> usize {
    use rvoip_sip_core::types::TypedHeader;
    let self_lower = self_host.to_ascii_lowercase();
    let mut removed = 0;

    // First pass: filter each RecordRoute header's entries.
    for header in request.headers.iter_mut() {
        if let TypedHeader::RecordRoute(rr) = header {
            let before = rr.0.len();
            rr.0.retain(|entry| {
                let host = entry.0.uri.host.to_string().to_ascii_lowercase();
                host == self_lower
            });
            removed += before - rr.0.len();
        }
    }

    // Second pass: drop any RecordRoute headers that became empty.
    request.headers.retain(|h| match h {
        TypedHeader::RecordRoute(rr) => !rr.0.is_empty(),
        _ => true,
    });

    removed
}

/// E4 / RFC 3261 §8.1.2: produce the full `extra_headers` list for an
/// outgoing INVITE, prepending a pre-loaded `Route` header when an outbound
/// proxy is configured on the `DialogAdapter`.
///
/// Pure so the "which headers travel on the wire" decision can be validated
/// without constructing a dialog_api / transport stack. Callers:
/// `DialogAdapter::send_invite_with_extra_headers`.
pub(crate) fn prepend_outbound_proxy_route(
    extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
) -> Vec<rvoip_sip_core::types::TypedHeader> {
    let mut headers = extra_headers;
    if let Some(uri) = outbound_proxy_uri {
        use rvoip_sip_core::types::{route::Route, TypedHeader};
        headers.insert(0, TypedHeader::Route(Route::with_uri(uri.clone())));
    }
    headers
}

/// SIP_API_DESIGN_2 §5.4 + §6.1 — the canonical pre-dispatch step for
/// every `send_*_with_options` mirror on [`DialogAdapter`]. Runs
/// [`crate::api::headers::policy::validate_outbound`] against the
/// application extras (catches stack-managed names that bypassed the
/// builder's strictness gate), then prepends the configured outbound
/// proxy's `Route:` header via [`prepend_outbound_proxy_route`].
///
/// Returns the rewritten extras vector or a typed `SessionError` if
/// the header policy rejects the staged set. The dialog-adapter
/// mirror passes the returned vector through to dialog-core.
pub(crate) fn apply_outbound_extras_policy(
    method: rvoip_sip_core::types::Method,
    extras: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
) -> Result<Vec<rvoip_sip_core::types::TypedHeader>> {
    if let Err(violations) = crate::api::headers::policy::validate_outbound(method, &extras) {
        // Map the first violation to SessionError::HeaderPolicy; the
        // policy returns the StackManaged-in-extras case as a
        // MissingRequiredHeader-shaped violation today.
        let first = violations.into_iter().next().expect("non-empty on Err");
        return Err(SessionError::HeaderPolicy {
            method: first.method,
            header: first.name,
            reason: crate::api::headers::ViolationReason::StackManaged,
        });
    }
    Ok(prepend_outbound_proxy_route(extras, outbound_proxy_uri))
}

/// SIP_API_DESIGN_2 R2 — auth-retry mirror of
/// [`apply_outbound_extras_policy`]. Runs the same policy validation
/// on the application extras, then **appends** the
/// `Authorization:` / `Proxy-Authorization:` header *after* policy
/// validation. The auth header bypasses the policy because:
///
/// 1. The HeaderPolicy classifies `Authorization` as `MethodShaped`
///    for INVITE / REGISTER / SUBSCRIBE / MESSAGE / OPTIONS / REFER,
///    meaning application code can't stage it via `with_raw_header`.
/// 2. But the state machine *itself* stages it on the auth-retry hop
///    via `Action::SendRequestWithAuth`, computed from the digest
///    challenge. That's a stack-managed injection, not an application
///    one, so the policy guard is intentionally bypassed.
///
/// `auth_header_name` is the raw wire name (`"Authorization"` or
/// `"Proxy-Authorization"`); `auth_header_value` is the rendered
/// `Digest username="..", ...` body.
pub(crate) fn apply_outbound_extras_policy_with_auth(
    method: rvoip_sip_core::types::Method,
    extras: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
    auth_header_name: &str,
    auth_header_value: String,
) -> Result<Vec<rvoip_sip_core::types::TypedHeader>> {
    let mut validated = apply_outbound_extras_policy(method, extras, outbound_proxy_uri)?;
    let header_name = match auth_header_name {
        "Proxy-Authorization" => rvoip_sip_core::types::header::HeaderName::ProxyAuthorization,
        _ => rvoip_sip_core::types::header::HeaderName::Authorization,
    };
    validated.push(rvoip_sip_core::types::TypedHeader::Other(
        header_name,
        rvoip_sip_core::types::headers::HeaderValue::Raw(auth_header_value.into_bytes()),
    ));
    Ok(validated)
}