rustpbx 0.4.2

A SIP PBX implementation in Rust
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
#[cfg(test)]
mod callsession_b2bua_tests {
    use super::super::media_bridge::MediaBridge;
    use super::super::session::NegotiationState;
    use super::super::test_util::tests::MockMediaPeer;
    use crate::call::{DialStrategy, DialplanFlow};
    use crate::media::negotiate::{CodecInfo, MediaNegotiator};
    // use crate::proxy::tests::common::create_test_server;
    use audio_codec::CodecType;
    use rustrtc::RtpCodecParameters;
    use std::sync::Arc;

    // ==================== Helper Functions ====================

    /// Create a mock RTP codec parameters for testing
    fn mock_rtp_params(payload_type: u8, clock_rate: u32, channels: u8) -> RtpCodecParameters {
        RtpCodecParameters {
            payload_type,
            clock_rate,
            channels,
        }
    }

    /// Create a simple SDP offer with specified codec
    fn create_sdp_offer(codec: &str, payload_type: u8) -> String {
        format!(
            "v=0\r\n\
             o=- 1234567890 1234567890 IN IP4 192.168.1.1\r\n\
             s=-\r\n\
             c=IN IP4 192.168.1.1\r\n\
             t=0 0\r\n\
             m=audio 10000 RTP/AVP {}\r\n\
             a=rtpmap:{} {}\r\n",
            payload_type, payload_type, codec
        )
    }

    /// Create a simple SDP answer with specified codec
    fn create_sdp_answer(codec: &str, payload_type: u8) -> String {
        format!(
            "v=0\r\n\
             o=- 9876543210 9876543210 IN IP4 192.168.1.2\r\n\
             s=-\r\n\
             c=IN IP4 192.168.1.2\r\n\
             t=0 0\r\n\
             m=audio 20000 RTP/AVP {}\r\n\
             a=rtpmap:{} {}\r\n",
            payload_type, payload_type, codec
        )
    }

    // ==================== Test 1: Basic Forwarding Scenarios ====================

    #[tokio::test]
    async fn test_simple_forward_pcmu_to_pcmu() {
        // Test: A -> B with same codec (PCMU), should use zero-copy forwarding
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let params_a = mock_rtp_params(0, 8000, 1);
        let params_b = mock_rtp_params(0, 8000, 1);

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            params_a,
            params_b,
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_simple_forward_pcmu_to_pcmu".to_string(),
            None,
        );

        // Should NOT require transcoding
        assert_eq!(bridge.codec_a, CodecType::PCMU);
        assert_eq!(bridge.codec_b, CodecType::PCMU);

        bridge
            .start()
            .await
            .expect("Bridge should start successfully");
        bridge.stop();

        assert!(leg_a.stop_count() > 0);
        assert!(leg_b.stop_count() > 0);
    }

    #[tokio::test]
    async fn test_forward_opus_to_pcmu_transcoding() {
        // Test: A (Opus) -> B (PCMU), should require transcoding
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let params_a = mock_rtp_params(111, 48000, 2);
        let params_b = mock_rtp_params(0, 8000, 1);

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            params_a,
            params_b,
            vec![],
            vec![],
            CodecType::Opus,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_forward_opus_to_pcmu_transcoding".to_string(),
            None,
        );

        // Should require transcoding
        assert_eq!(bridge.codec_a, CodecType::Opus);
        assert_eq!(bridge.codec_b, CodecType::PCMU);

        bridge
            .start()
            .await
            .expect("Bridge should start successfully");

        // Verify bridge handles transcoding path
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        bridge.stop();
    }

    #[tokio::test]
    async fn test_pcma_to_pcmu_transcoding() {
        // Test: A (PCMA) -> B (PCMU), should require transcoding
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let params_a = mock_rtp_params(8, 8000, 1);
        let params_b = mock_rtp_params(0, 8000, 1);

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            params_a.clone(),
            params_b.clone(),
            vec![],
            vec![],
            CodecType::PCMA,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_pcma_to_pcmu_transcoding".to_string(),
            None,
        );

        // Should require transcoding
        assert_eq!(bridge.codec_a, CodecType::PCMA);
        assert_eq!(bridge.codec_b, CodecType::PCMU);

        bridge
            .start()
            .await
            .expect("Bridge should start successfully");
        bridge.stop();
    }

    // ==================== Test 2: Codec Negotiation Scenarios ====================

    #[test]
    fn test_parse_rtp_map_from_sdp_multi_codec() {
        // Test: Parse SDP with multiple codecs
        let sdp = "v=0\r\n\
            o=- 8819118164752754436 2 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 53824 UDP/TLS/RTP/SAVPF 111 9 0 8\r\n\
            a=rtpmap:111 opus/48000/2\r\n\
            a=rtpmap:9 G722/8000\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=rtpmap:8 PCMA/8000\r\n\
            a=rtpmap:126 telephone-event/8000\r\n";

        let parsed_sdp = rustrtc::SessionDescription::parse(rustrtc::SdpType::Offer, sdp).unwrap();
        let section = parsed_sdp
            .media_sections
            .iter()
            .find(|m| m.kind == rustrtc::MediaKind::Audio)
            .unwrap();

        let rtp_map = MediaNegotiator::parse_rtp_map_from_section(section);

        // Verify all codecs are parsed
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 111 && *codec == CodecType::Opus)
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 9 && *codec == CodecType::G722)
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 0 && *codec == CodecType::PCMU)
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 8 && *codec == CodecType::PCMA)
        );
    }

    #[test]
    fn test_extract_codec_params_pcmu() {
        let sdp = create_sdp_answer("PCMU/8000/1", 0);
        let codecs = MediaNegotiator::extract_codec_params(&sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::PCMU);
        assert_eq!(params.payload_type, 0);
        assert_eq!(params.clock_rate, 8000);
        assert_eq!(params.channels, 1);
        assert!(codecs.dtmf.is_empty());
    }

    #[test]
    fn test_extract_codec_params_pcma() {
        let sdp = create_sdp_answer("PCMA/8000/1", 8);
        let codecs = MediaNegotiator::extract_codec_params(&sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::PCMA);
        assert_eq!(params.payload_type, 8);
        assert_eq!(params.clock_rate, 8000);
        assert_eq!(params.channels, 1);
    }

    #[test]
    fn test_extract_codec_params_opus() {
        let sdp = create_sdp_answer("opus/48000/2", 111);
        let codecs = MediaNegotiator::extract_codec_params(&sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::Opus);
        assert_eq!(params.payload_type, 111);
        assert_eq!(params.clock_rate, 48000);
        assert_eq!(params.channels, 2);
    }

    #[test]
    fn test_extract_codec_params_g722() {
        let sdp = create_sdp_answer("G722/8000", 9);
        let codecs = MediaNegotiator::extract_codec_params(&sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::G722);
        assert_eq!(params.payload_type, 9);
        assert_eq!(params.clock_rate, 8000);
    }

    #[test]
    fn test_dtmf_payload_extraction() {
        let sdp = "v=0\r\n\
            o=- 1234567890 1234567890 IN IP4 192.168.1.1\r\n\
            s=-\r\n\
            c=IN IP4 192.168.1.1\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0 101\r\n\
            a=rtpmap:0 PCMU/8000/1\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let codecs = MediaNegotiator::extract_codec_params(sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::PCMU);
        assert_eq!(params.payload_type, 0);
        assert_eq!(
            codecs
                .dtmf
                .iter()
                .map(|codec| codec.payload_type)
                .collect::<Vec<_>>(),
            vec![101]
        );
    }

    // ==================== Test 3: Codec Compatibility Scenarios ====================

    #[test]
    fn test_codec_compatibility_exact_match() {
        // Both sides support PCMU - should match without transcoding
        let alice_offer = create_sdp_offer("PCMU/8000/1", 0);
        let bob_answer = create_sdp_answer("PCMU/8000/1", 0);

        let alice_codecs = MediaNegotiator::extract_codec_params(&alice_offer).audio;
        let bob_codecs = MediaNegotiator::extract_codec_params(&bob_answer).audio;
        let bob_codec = bob_codecs[0].codec;

        // Verify Alice supports Bob's chosen codec
        let compatible = alice_codecs.iter().any(|c| c.codec == bob_codec);

        assert!(compatible, "Alice should support PCMU");
        assert_eq!(bob_codec, CodecType::PCMU);
    }

    #[test]
    fn test_codec_incompatibility_requires_transcoding() {
        // Alice only supports Opus, Bob only supports PCMU - requires transcoding
        let alice_offer = create_sdp_offer("opus/48000/2", 111);
        let bob_answer = create_sdp_answer("PCMU/8000/1", 0);

        let alice_sdp =
            rustrtc::SessionDescription::parse(rustrtc::SdpType::Offer, &alice_offer).unwrap();
        let alice_section = alice_sdp
            .media_sections
            .iter()
            .find(|m| m.kind == rustrtc::MediaKind::Audio)
            .unwrap();
        let alice_codecs = MediaNegotiator::parse_rtp_map_from_section(alice_section);

        let bob_codecs = MediaNegotiator::extract_codec_params(&bob_answer).audio;
        let bob_codec = bob_codecs[0].codec;

        // Verify Alice does NOT support Bob's codec
        let compatible = alice_codecs
            .iter()
            .any(|(_, (codec, _, _))| *codec == bob_codec);

        assert!(
            !compatible,
            "Alice should NOT support PCMU - transcoding required"
        );
        assert_eq!(bob_codec, CodecType::PCMU);
    }

    // ==================== Test 4: MediaBridge Advanced Scenarios ====================

    #[tokio::test]
    async fn test_bridge_supports_suppress_and_resume() {
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_bridge_supports_suppress_and_resume".to_string(),
            None,
        );

        bridge.start().await.expect("Bridge should start");

        // Test suppress and resume
        bridge
            .suppress_forwarding("test-track")
            .await
            .expect("Should suppress");
        bridge
            .resume_forwarding("test-track")
            .await
            .expect("Should resume");

        bridge.stop();
    }

    #[tokio::test]
    async fn test_bridge_multiple_start_is_idempotent() {
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_bridge_multiple_start_is_idempotent".to_string(),
            None,
        );

        // Starting multiple times should be safe
        bridge.start().await.expect("First start should succeed");
        bridge.start().await.expect("Second start should succeed");
        bridge.start().await.expect("Third start should succeed");

        bridge.stop();
    }

    // ==================== Test 5: Negotiation State Machine ====================

    #[test]
    fn test_negotiation_state_transitions() {
        // Test the NegotiationState enum transitions
        let idle = NegotiationState::Idle;
        let stable = NegotiationState::Stable;
        let local_offer = NegotiationState::LocalOfferSent;
        let remote_offer = NegotiationState::RemoteOfferReceived;

        // Verify states are distinct
        assert_ne!(idle, stable);
        assert_ne!(idle, local_offer);
        assert_ne!(idle, remote_offer);
        assert_ne!(stable, local_offer);
        assert_ne!(stable, remote_offer);
        assert_ne!(local_offer, remote_offer);

        // Verify Copy and Clone work
        let copied = stable;
        assert_eq!(copied, stable);
    }

    // ==================== Test 6: DTMF Handling ====================

    #[tokio::test]
    async fn test_bridge_with_dtmf_payload_types() {
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![CodecInfo {
                payload_type: 101,
                codec: CodecType::TelephoneEvent,
                clock_rate: 8000,
                channels: 1,
            }],
            vec![CodecInfo {
                payload_type: 101,
                codec: CodecType::TelephoneEvent,
                clock_rate: 8000,
                channels: 1,
            }],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_bridge_with_dtmf_payload_types".to_string(),
            None,
        );

        assert_eq!(bridge.dtmf_codecs_a.len(), 1);
        assert_eq!(bridge.dtmf_codecs_b.len(), 1);

        bridge.start().await.expect("Bridge should start");
        bridge.stop();
    }

    // ==================== Test 7: Error Handling Scenarios ====================

    #[test]
    fn test_dialplan_flow_validation() {
        // Test empty targets
        let empty_strategy = DialStrategy::Sequential(vec![]);
        let flow = DialplanFlow::Targets(empty_strategy);

        // This should work without panic
        assert!(matches!(flow, DialplanFlow::Targets(_)));
    }

    // ==================== Test 8: Codec Parameters Validation ====================

    #[test]
    fn test_rtp_params_clock_rates() {
        // PCMU/PCMA should use 8000 Hz
        let pcmu_params = mock_rtp_params(0, 8000, 1);
        assert_eq!(pcmu_params.clock_rate, 8000);
        assert_eq!(pcmu_params.channels, 1);

        // Opus should use 48000 Hz
        let opus_params = mock_rtp_params(111, 48000, 2);
        assert_eq!(opus_params.clock_rate, 48000);
        assert_eq!(opus_params.channels, 2);

        // G722 should use 8000 Hz (despite 16kHz sampling)
        let g722_params = mock_rtp_params(9, 8000, 1);
        assert_eq!(g722_params.clock_rate, 8000);
    }

    #[tokio::test]
    async fn test_bridge_without_recorder() {
        // Test that bridge works when recorder is disabled
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_bridge_without_recorder".to_string(),
            None,
        );

        // Should work fine without recorder
        bridge
            .start()
            .await
            .expect("Bridge should start without recorder");
        bridge.stop();
    }

    #[test]
    fn test_queue_plan_creation() {
        use crate::call::{DialStrategy, Location, QueuePlan};
        use rsipstack::sip::Uri;

        let target1 = Location {
            aor: Uri::try_from("sip:agent1@example.com").unwrap(),
            expires: 3600,
            ..Default::default()
        };

        let mut plan = QueuePlan::default();
        plan.dial_strategy = Some(DialStrategy::Sequential(vec![target1]));
        plan.accept_immediately = true;

        assert!(plan.accept_immediately);
        assert!(plan.dial_strategy.is_some());
    }

    #[test]
    fn test_queue_plan_with_hold_config() {
        use crate::call::{QueueHoldConfig, QueuePlan};

        let mut plan = QueuePlan::default();
        plan.hold = Some(QueueHoldConfig {
            audio_file: Some("/audio/hold-music.wav".to_string()),
            loop_playback: true,
        });

        assert!(plan.hold.is_some());
        assert_eq!(
            plan.hold.as_ref().unwrap().audio_file,
            Some("/audio/hold-music.wav".to_string())
        );
        assert!(plan.hold.as_ref().unwrap().loop_playback);
    }

    #[test]
    fn test_queue_plan_fallback_actions() {
        use crate::call::{FailureAction, QueueFallbackAction, QueuePlan};
        use rsipstack::sip::StatusCode;

        let mut plan = QueuePlan::default();

        // Test with failure action fallback
        plan.fallback = Some(QueueFallbackAction::Failure(
            FailureAction::PlayThenHangup {
                audio_file: "/audio/unavailable.wav".to_string(),
                use_early_media: false,
                status_code: StatusCode::TemporarilyUnavailable,
                reason: Some("All agents busy".to_string()),
            },
        ));

        assert!(plan.fallback.is_some());
    }

    #[test]
    fn test_dialplan_flow_queue_construction() {
        use crate::call::{DialStrategy, DialplanFlow, Location, QueuePlan};
        use rsipstack::sip::Uri;

        let target = Location {
            aor: Uri::try_from("sip:agent1@example.com").unwrap(),
            expires: 3600,
            ..Default::default()
        };

        let mut plan = QueuePlan::default();
        plan.dial_strategy = Some(DialStrategy::Sequential(vec![target.clone()]));

        // Create a Queue flow with a fallback to a simple target
        let fallback = DialplanFlow::Targets(DialStrategy::Sequential(vec![target]));
        let queue_flow = DialplanFlow::Queue {
            plan,
            next: Box::new(fallback),
        };

        // Verify structure
        match queue_flow {
            DialplanFlow::Queue { plan: _, next } => {
                assert!(matches!(*next, DialplanFlow::Targets(_)));
            }
            _ => panic!("Expected Queue flow"),
        }
    }

    // Note: QueueExecutor tests removed as the executor is no longer used.
    // Queue functionality is now integrated directly into CallSession via execute_queue_plan()

    #[test]
    fn test_dialplan_flow_queue_with_multiple_fallback_levels() {
        use crate::call::{DialStrategy, DialplanFlow, Location, QueuePlan};
        use rsipstack::sip::Uri;

        let target1 = Location {
            aor: Uri::try_from("sip:agent1@example.com").unwrap(),
            expires: 3600,
            ..Default::default()
        };

        let target2 = Location {
            aor: Uri::try_from("sip:agent2@example.com").unwrap(),
            expires: 3600,
            ..Default::default()
        };

        // Create primary queue
        let mut primary_queue = QueuePlan::default();
        primary_queue.dial_strategy = Some(DialStrategy::Sequential(vec![target1]));
        primary_queue.label = Some("Primary Queue".to_string());

        // Create fallback queue
        let mut fallback_queue = QueuePlan::default();
        fallback_queue.dial_strategy = Some(DialStrategy::Sequential(vec![target2.clone()]));
        fallback_queue.label = Some("Fallback Queue".to_string());

        // Create final fallback to direct dial
        let final_fallback = DialplanFlow::Targets(DialStrategy::Sequential(vec![target2]));

        // Build nested queue flows
        let fallback_queue_flow = DialplanFlow::Queue {
            plan: fallback_queue,
            next: Box::new(final_fallback),
        };

        let primary_queue_flow = DialplanFlow::Queue {
            plan: primary_queue,
            next: Box::new(fallback_queue_flow),
        };

        // Verify structure
        match primary_queue_flow {
            DialplanFlow::Queue { plan, next } => {
                assert_eq!(plan.label, Some("Primary Queue".to_string()));
                match *next {
                    DialplanFlow::Queue {
                        plan: fallback_plan,
                        next: final_next,
                    } => {
                        assert_eq!(fallback_plan.label, Some("Fallback Queue".to_string()));
                        assert!(matches!(*final_next, DialplanFlow::Targets(_)));
                    }
                    _ => panic!("Expected nested Queue flow"),
                }
            }
            _ => panic!("Expected Queue flow"),
        }
    }

    #[test]
    fn test_queue_plan_without_dial_strategy() {
        use crate::call::QueuePlan;

        let plan = QueuePlan {
            accept_immediately: false,
            passthrough_ringback: false,
            hold: None,
            fallback: None,
            dial_strategy: None, // No targets
            ring_timeout: None,
            label: Some("Empty Queue".to_string()),
            ..Default::default()
        };

        // Should be valid to create, but execution will fail gracefully
        assert_eq!(plan.label, Some("Empty Queue".to_string()));
        assert!(plan.dial_strategy.is_none());
    }

    // ==================== Test 9: MediaBridge Drop Behavior ====================

    #[tokio::test]
    async fn test_media_bridge_drop_calls_stop_on_legs() {
        use super::super::test_util::tests::MockMediaPeer;

        // Create mock peers with stop tracking
        let leg_a = Arc::new(MockMediaPeer::new_with_stop_tracking());
        let leg_b = Arc::new(MockMediaPeer::new_with_stop_tracking());

        // Initially stop should not have been called
        assert_eq!(leg_a.stop_count(), 0);
        assert_eq!(leg_b.stop_count(), 0);

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_media_bridge_drop_calls_stop_on_legs".to_string(),
            None,
        );

        // Start the bridge
        bridge.start().await.expect("Bridge should start");

        // Drop the bridge - this should trigger Drop which calls stop() on legs
        drop(bridge);

        // Verify stop was called on both legs
        assert_eq!(
            leg_a.stop_count(),
            1,
            "leg_a.stop() should be called exactly once on Drop"
        );
        assert_eq!(
            leg_b.stop_count(),
            1,
            "leg_b.stop() should be called exactly once on Drop"
        );
    }

    #[tokio::test]
    async fn test_media_bridge_drop_idempotent() {
        use super::super::test_util::tests::MockMediaPeer;

        let leg_a = Arc::new(MockMediaPeer::new_with_stop_tracking());
        let leg_b = Arc::new(MockMediaPeer::new_with_stop_tracking());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_media_bridge_drop_idempotent".to_string(),
            None,
        );

        bridge.start().await.expect("Bridge should start");

        // Call stop explicitly first
        bridge.stop();

        // Then drop - stop should only be called once total
        drop(bridge);

        assert_eq!(
            leg_a.stop_count(),
            1,
            "leg_a.stop() should be called exactly once even if stopped before drop"
        );
        assert_eq!(
            leg_b.stop_count(),
            1,
            "leg_b.stop() should be called exactly once even if stopped before drop"
        );
    }

    #[tokio::test]
    async fn test_media_bridge_stop_can_be_called_multiple_times() {
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_media_bridge_stop_multiple".to_string(),
            None,
        );

        bridge.start().await.expect("Bridge should start");

        // Calling stop multiple times should be safe
        bridge.stop();
        bridge.stop();
        bridge.stop();

        // All legs should have stop called at least once
        assert!(leg_a.stop_count() > 0);
        assert!(leg_b.stop_count() > 0);
    }

    // ==================== Test 10: SDP Parsing Idempotence ====================

    #[test]
    fn test_extract_codec_params_is_idempotent() {
        let sdp = "v=0\r\n\
            o=- 8819118164752754436 2 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 53824 UDP/TLS/RTP/SAVPF 111 9 0 8\r\n\
            a=rtpmap:111 opus/48000/2\r\n\
            a=rtpmap:9 G722/8000\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=rtpmap:8 PCMA/8000\r\n\
            a=rtpmap:126 telephone-event/8000\r\n";

        // Parse multiple times and verify results are consistent
        let result1 = MediaNegotiator::extract_codec_params(sdp);
        let result2 = MediaNegotiator::extract_codec_params(sdp);
        let result3 = MediaNegotiator::extract_codec_params(sdp);

        assert_eq!(
            result1.audio.len(),
            result2.audio.len(),
            "Audio codec count should be consistent"
        );
        assert_eq!(
            result1.audio.len(),
            result3.audio.len(),
            "Audio codec count should be consistent"
        );

        // Verify all parsed codecs are the same
        for i in 0..result1.audio.len() {
            assert_eq!(
                result1.audio[i].codec, result2.audio[i].codec,
                "Codec at position {} should be the same",
                i
            );
            assert_eq!(
                result1.audio[i].payload_type, result2.audio[i].payload_type,
                "Payload type at position {} should be the same",
                i
            );
        }
    }

    #[test]
    fn test_extract_codec_params_twice_does_not_double_dtmf() {
        let sdp = "v=0\r\n\
            o=- 1234567890 1234567890 IN IP4 192.168.1.1\r\n\
            s=-\r\n\
            c=IN IP4 192.168.1.1\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0 101\r\n\
            a=rtpmap:0 PCMU/8000/1\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let result1 = MediaNegotiator::extract_codec_params(sdp);
        let result2 = MediaNegotiator::extract_codec_params(sdp);

        // DTMF codecs should not be duplicated
        let dtmf_count_1 = result1.dtmf.len();
        let dtmf_count_2 = result2.dtmf.len();
        assert_eq!(
            dtmf_count_1, dtmf_count_2,
            "DTMF codec count should be consistent"
        );
    }

    // ==================== Test 11: NegotiationState Transitions ====================

    #[test]
    fn test_negotiation_state_ordering() {
        use super::super::session::NegotiationState;

        // Verify we can compare states
        let states = [
            NegotiationState::Idle,
            NegotiationState::LocalOfferSent,
            NegotiationState::RemoteOfferReceived,
            NegotiationState::Stable,
        ];

        // All states should be different
        for (i, state1) in states.iter().enumerate() {
            for (j, state2) in states.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        state1, state2,
                        "States at different positions should not be equal"
                    );
                }
            }
        }
    }

    // ==================== Test 12: Reporter Channel Handling ====================

    #[tokio::test]
    async fn test_media_bridge_with_mock_tracks_get_tracks_called() {
        use super::super::test_util::tests::MockMediaPeer;

        let leg_a = Arc::new(MockMediaPeer::new_with_stop_tracking());
        let leg_b = Arc::new(MockMediaPeer::new_with_stop_tracking());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_get_tracks_called".to_string(),
            None,
        );

        bridge.start().await.expect("Bridge should start");

        // Verify get_tracks was called on both legs during start
        // Note: start() calls get_tracks() internally
        assert!(
            leg_a.get_tracks_call_count() > 0 || leg_b.get_tracks_call_count() > 0,
            "get_tracks should be called at least once during start"
        );

        bridge.stop();
    }

    // ==================== Test 13: Bridge Start Is Idempotent ====================

    #[tokio::test]
    async fn test_bridge_start_idempotent_multiple_calls() {
        let leg_a = Arc::new(MockMediaPeer::new());
        let leg_b = Arc::new(MockMediaPeer::new());

        let bridge = MediaBridge::new(
            leg_a.clone(),
            leg_b.clone(),
            mock_rtp_params(0, 8000, 1),
            mock_rtp_params(0, 8000, 1),
            vec![],
            vec![],
            CodecType::PCMU,
            CodecType::PCMU,
            None,
            None,
            None,
            "test_bridge_start_idempotent".to_string(),
            None,
        );

        // Start multiple times - should all succeed
        for _ in 0..5 {
            bridge.start().await.expect("start() should be idempotent");
        }

        // Only one stop needed
        bridge.stop();
    }
}