rs-pfcp 0.4.0

High-performance Rust implementation of PFCP (Packet Forwarding Control Protocol) for 5G networks with 100% 3GPP TS 29.244 Release 18 compliance
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
//! CreateURR IE and its sub-IEs.

use crate::error::PfcpError;
use crate::ie::{
    inactivity_detection_time::InactivityDetectionTime, marshal_ies,
    measurement_method::MeasurementMethod, measurement_period::MeasurementPeriod,
    monitoring_time::MonitoringTime, reporting_triggers::ReportingTriggers,
    subsequent_time_threshold::SubsequentTimeThreshold,
    subsequent_volume_threshold::SubsequentVolumeThreshold, time_quota::TimeQuota,
    time_threshold::TimeThreshold, urr_id::UrrId, volume_quota::VolumeQuota,
    volume_threshold::VolumeThreshold, Ie, IeIterator, IeType,
};

/// Represents the Create URR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateUrr {
    pub urr_id: UrrId,
    pub measurement_method: MeasurementMethod,
    pub reporting_triggers: ReportingTriggers,
    pub monitoring_time: Option<MonitoringTime>,
    pub volume_threshold: Option<VolumeThreshold>,
    pub time_threshold: Option<TimeThreshold>,
    pub subsequent_volume_threshold: Option<SubsequentVolumeThreshold>,
    pub subsequent_time_threshold: Option<SubsequentTimeThreshold>,
    pub inactivity_detection_time: Option<InactivityDetectionTime>,
    /// Hard volume limit — UPF drops packets after quota is exhausted.
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 73.
    pub volume_quota: Option<VolumeQuota>,
    /// Hard time limit — UPF terminates sessions after quota is exhausted.
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 74.
    pub time_quota: Option<TimeQuota>,
    /// Periodic measurement reporting interval in seconds.
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 64.
    pub measurement_period: Option<MeasurementPeriod>,
}

impl CreateUrr {
    /// Creates a new Create URR IE.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        urr_id: UrrId,
        measurement_method: MeasurementMethod,
        reporting_triggers: ReportingTriggers,
        monitoring_time: Option<MonitoringTime>,
        volume_threshold: Option<VolumeThreshold>,
        time_threshold: Option<TimeThreshold>,
        subsequent_volume_threshold: Option<SubsequentVolumeThreshold>,
        subsequent_time_threshold: Option<SubsequentTimeThreshold>,
        inactivity_detection_time: Option<InactivityDetectionTime>,
    ) -> Self {
        CreateUrr {
            urr_id,
            measurement_method,
            reporting_triggers,
            monitoring_time,
            volume_threshold,
            time_threshold,
            subsequent_volume_threshold,
            subsequent_time_threshold,
            inactivity_detection_time,
            volume_quota: None,
            time_quota: None,
            measurement_period: None,
        }
    }

    /// Returns a builder for constructing a Create URR IE.
    pub fn builder(urr_id: UrrId) -> CreateUrrBuilder {
        CreateUrrBuilder::new(urr_id)
    }

    /// Marshals the Create URR into a byte vector.
    pub fn marshal(&self) -> Vec<u8> {
        let mut ies = vec![
            self.urr_id.to_ie(),
            self.measurement_method.to_ie(),
            self.reporting_triggers.to_ie(),
        ];

        if let Some(mt) = &self.monitoring_time {
            ies.push(Ie::new(IeType::MonitoringTime, mt.marshal().to_vec()));
        }
        if let Some(vt) = &self.volume_threshold {
            ies.push(Ie::new(IeType::VolumeThreshold, vt.marshal()));
        }
        if let Some(tt) = &self.time_threshold {
            ies.push(Ie::new(IeType::TimeThreshold, tt.marshal().to_vec()));
        }
        if let Some(svt) = &self.subsequent_volume_threshold {
            ies.push(Ie::new(IeType::SubsequentVolumeThreshold, svt.marshal()));
        }
        if let Some(stt) = &self.subsequent_time_threshold {
            ies.push(Ie::new(
                IeType::SubsequentTimeThreshold,
                stt.marshal().to_vec(),
            ));
        }
        if let Some(idt) = &self.inactivity_detection_time {
            ies.push(Ie::new(
                IeType::InactivityDetectionTime,
                idt.marshal().to_vec(),
            ));
        }
        if let Some(vq) = &self.volume_quota {
            ies.push(Ie::new(
                IeType::VolumeQuota,
                vq.marshal()
                    .expect("VolumeQuota marshal should not fail for a well-formed value"),
            ));
        }
        if let Some(tq) = &self.time_quota {
            ies.push(Ie::new(IeType::TimeQuota, tq.marshal()));
        }
        if let Some(mp) = &self.measurement_period {
            ies.push(Ie::new(IeType::MeasurementPeriod, mp.marshal().to_vec()));
        }

        marshal_ies(&ies)
    }

    /// Unmarshals a byte slice into a Create Urr IE.
    pub fn unmarshal(payload: &[u8]) -> Result<Self, PfcpError> {
        let mut urr_id = None;
        let mut measurement_method = None;
        let mut reporting_triggers = None;
        let mut monitoring_time = None;
        let mut volume_threshold = None;
        let mut time_threshold = None;
        let mut subsequent_volume_threshold = None;
        let mut subsequent_time_threshold = None;
        let mut inactivity_detection_time = None;
        let mut volume_quota = None;
        let mut time_quota = None;
        let mut measurement_period = None;

        for ie_result in IeIterator::new(payload) {
            let ie = ie_result?;
            match ie.ie_type {
                IeType::UrrId => {
                    urr_id = Some(UrrId::unmarshal(&ie.payload)?);
                }
                IeType::MeasurementMethod => {
                    measurement_method = Some(MeasurementMethod::unmarshal(&ie.payload)?);
                }
                IeType::ReportingTriggers => {
                    reporting_triggers = Some(ReportingTriggers::unmarshal(&ie.payload)?);
                }
                IeType::MonitoringTime => {
                    monitoring_time = Some(MonitoringTime::unmarshal(&ie.payload)?);
                }
                IeType::VolumeThreshold => {
                    volume_threshold = Some(VolumeThreshold::unmarshal(&ie.payload)?);
                }
                IeType::TimeThreshold => {
                    time_threshold = Some(TimeThreshold::unmarshal(&ie.payload)?);
                }
                IeType::SubsequentVolumeThreshold => {
                    subsequent_volume_threshold =
                        Some(SubsequentVolumeThreshold::unmarshal(&ie.payload)?);
                }
                IeType::SubsequentTimeThreshold => {
                    subsequent_time_threshold =
                        Some(SubsequentTimeThreshold::unmarshal(&ie.payload)?);
                }
                IeType::InactivityDetectionTime => {
                    inactivity_detection_time =
                        Some(InactivityDetectionTime::unmarshal(&ie.payload)?);
                }
                IeType::VolumeQuota => {
                    volume_quota = Some(VolumeQuota::unmarshal(&ie.payload)?);
                }
                IeType::TimeQuota => {
                    time_quota = Some(TimeQuota::unmarshal(&ie.payload)?);
                }
                IeType::MeasurementPeriod => {
                    measurement_period = Some(MeasurementPeriod::unmarshal(&ie.payload)?);
                }
                _ => (),
            }
        }

        Ok(CreateUrr {
            urr_id: urr_id.ok_or(PfcpError::missing_ie_in_grouped(
                IeType::UrrId,
                IeType::CreateUrr,
            ))?,
            measurement_method: measurement_method.ok_or(PfcpError::missing_ie_in_grouped(
                IeType::MeasurementMethod,
                IeType::CreateUrr,
            ))?,
            reporting_triggers: reporting_triggers.ok_or(PfcpError::missing_ie_in_grouped(
                IeType::ReportingTriggers,
                IeType::CreateUrr,
            ))?,
            monitoring_time,
            volume_threshold,
            time_threshold,
            subsequent_volume_threshold,
            subsequent_time_threshold,
            inactivity_detection_time,
            volume_quota,
            time_quota,
            measurement_period,
        })
    }

    /// Wraps the Create URR in a CreateUrr IE.
    pub fn to_ie(&self) -> Ie {
        Ie::new(IeType::CreateUrr, self.marshal())
    }
}

/// Builder for constructing Create URR IEs with a fluent API.
///
/// The builder pattern provides an ergonomic way to construct Create URR IEs
/// with proper validation and convenient methods for common usage patterns.
///
/// # Required Fields
/// - `urr_id`: URR ID (set in `new()`)
/// - `measurement_method`: How to measure usage
/// - `reporting_triggers`: When to report
///
/// # Optional Fields
/// - `monitoring_time`: When to start/stop monitoring
/// - `volume_threshold`: Volume limit before reporting
/// - `time_threshold`: Time limit before reporting
/// - `subsequent_volume_threshold`: Volume limit after first report
/// - `subsequent_time_threshold`: Time limit after first report
/// - `inactivity_detection_time`: Detect inactive sessions
///
/// # Examples
///
/// ```rust
/// use rs_pfcp::ie::create_urr::CreateUrrBuilder;
/// use rs_pfcp::ie::urr_id::UrrId;
/// use rs_pfcp::ie::measurement_method::MeasurementMethod;
/// use rs_pfcp::ie::reporting_triggers::ReportingTriggers;
///
/// // Simple volume-based URR
/// let urr = CreateUrrBuilder::new(UrrId::new(1))
///     .measurement_method(MeasurementMethod::new(false, true, false)) // volume enabled
///     .reporting_triggers(ReportingTriggers::new())
///     .volume_threshold_bytes(1_000_000_000) // 1GB
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct CreateUrrBuilder {
    urr_id: Option<UrrId>,
    measurement_method: Option<MeasurementMethod>,
    reporting_triggers: Option<ReportingTriggers>,
    monitoring_time: Option<MonitoringTime>,
    volume_threshold: Option<VolumeThreshold>,
    time_threshold: Option<TimeThreshold>,
    subsequent_volume_threshold: Option<SubsequentVolumeThreshold>,
    subsequent_time_threshold: Option<SubsequentTimeThreshold>,
    inactivity_detection_time: Option<InactivityDetectionTime>,
    volume_quota: Option<VolumeQuota>,
    time_quota: Option<TimeQuota>,
    measurement_period: Option<MeasurementPeriod>,
}

impl CreateUrrBuilder {
    /// Creates a new Create URR builder with the specified URR ID.
    ///
    /// URR ID is mandatory for all URR instances.
    pub fn new(urr_id: UrrId) -> Self {
        CreateUrrBuilder {
            urr_id: Some(urr_id),
            ..Default::default()
        }
    }

    /// Sets the measurement method.
    ///
    /// This is a required field that specifies how to measure usage (volume, duration, event).
    pub fn measurement_method(mut self, method: MeasurementMethod) -> Self {
        self.measurement_method = Some(method);
        self
    }

    /// Sets the reporting triggers.
    ///
    /// This is a required field that specifies when to generate usage reports.
    pub fn reporting_triggers(mut self, triggers: ReportingTriggers) -> Self {
        self.reporting_triggers = Some(triggers);
        self
    }

    /// Sets the monitoring time.
    ///
    /// Specifies when to start or stop monitoring.
    pub fn monitoring_time(mut self, time: MonitoringTime) -> Self {
        self.monitoring_time = Some(time);
        self
    }

    /// Sets the volume threshold.
    ///
    /// Report when traffic volume exceeds this threshold.
    pub fn volume_threshold(mut self, threshold: VolumeThreshold) -> Self {
        self.volume_threshold = Some(threshold);
        self
    }

    /// Convenience method to set volume threshold in bytes (total traffic).
    ///
    /// Creates a volume threshold for total traffic (uplink + downlink).
    pub fn volume_threshold_bytes(mut self, bytes: u64) -> Self {
        self.volume_threshold = Some(VolumeThreshold::new(
            true,  // total volume
            false, // not uplink only
            false, // not downlink only
            Some(bytes),
            None,
            None,
        ));
        self
    }

    /// Convenience method to set volume threshold for uplink and downlink separately.
    pub fn volume_threshold_uplink_downlink(mut self, uplink: u64, downlink: u64) -> Self {
        self.volume_threshold = Some(VolumeThreshold::new(
            false, // not total
            true,  // uplink
            true,  // downlink
            None,
            Some(uplink),
            Some(downlink),
        ));
        self
    }

    /// Sets the time threshold in seconds.
    ///
    /// Report when monitoring duration exceeds this threshold.
    pub fn time_threshold(mut self, threshold: TimeThreshold) -> Self {
        self.time_threshold = Some(threshold);
        self
    }

    /// Convenience method to set time threshold from seconds.
    pub fn time_threshold_seconds(mut self, seconds: u32) -> Self {
        self.time_threshold = Some(TimeThreshold::new(seconds));
        self
    }

    /// Sets the subsequent volume threshold.
    ///
    /// Volume threshold to use after the first report.
    pub fn subsequent_volume_threshold(mut self, threshold: SubsequentVolumeThreshold) -> Self {
        self.subsequent_volume_threshold = Some(threshold);
        self
    }

    /// Convenience method to set subsequent volume threshold in bytes.
    pub fn subsequent_volume_threshold_bytes(mut self, bytes: u64) -> Self {
        self.subsequent_volume_threshold = Some(SubsequentVolumeThreshold::new(
            true,  // total volume
            false, // not uplink only
            false, // not downlink only
            Some(bytes),
            None,
            None,
        ));
        self
    }

    /// Sets the subsequent time threshold.
    ///
    /// Time threshold to use after the first report.
    pub fn subsequent_time_threshold(mut self, threshold: SubsequentTimeThreshold) -> Self {
        self.subsequent_time_threshold = Some(threshold);
        self
    }

    /// Convenience method to set subsequent time threshold from seconds.
    pub fn subsequent_time_threshold_seconds(mut self, seconds: u32) -> Self {
        self.subsequent_time_threshold = Some(SubsequentTimeThreshold::new(seconds));
        self
    }

    /// Sets the inactivity detection time.
    ///
    /// Detect when a session becomes inactive after this duration.
    pub fn inactivity_detection_time(mut self, time: InactivityDetectionTime) -> Self {
        self.inactivity_detection_time = Some(time);
        self
    }

    /// Convenience method to set inactivity detection time from seconds.
    pub fn inactivity_detection_time_seconds(mut self, seconds: u32) -> Self {
        self.inactivity_detection_time = Some(InactivityDetectionTime::new(seconds));
        self
    }

    /// Sets the volume quota — a hard limit after which the UPF drops packets.
    ///
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 73.
    pub fn volume_quota(mut self, quota: VolumeQuota) -> Self {
        self.volume_quota = Some(quota);
        self
    }

    /// Convenience method: set a total volume quota in bytes.
    pub fn volume_quota_bytes(mut self, bytes: u64) -> Self {
        self.volume_quota = Some(VolumeQuota::new(0x01, Some(bytes), None, None));
        self
    }

    /// Sets the time quota — a hard time limit after which the UPF terminates the session.
    ///
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 74.
    pub fn time_quota(mut self, quota: TimeQuota) -> Self {
        self.time_quota = Some(quota);
        self
    }

    /// Convenience method: set a time quota in seconds.
    pub fn time_quota_seconds(mut self, seconds: u32) -> Self {
        self.time_quota = Some(TimeQuota::new(seconds));
        self
    }

    /// Sets the measurement period for periodic reporting in seconds.
    ///
    /// Per 3GPP TS 29.244 Table 7.5.2.6-1, IE Type 64.
    pub fn measurement_period(mut self, period: MeasurementPeriod) -> Self {
        self.measurement_period = Some(period);
        self
    }

    /// Convenience method: set the measurement period from seconds.
    pub fn measurement_period_seconds(mut self, seconds: u32) -> Self {
        self.measurement_period = Some(MeasurementPeriod::new(seconds));
        self
    }

    /// Builds the Create URR IE with comprehensive validation.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Required fields are missing (URR ID, measurement method, reporting triggers)
    /// - Measurement method and threshold combinations are inconsistent:
    ///   - Volume measurement enabled but no volume threshold set
    ///   - Duration measurement enabled but no time threshold set
    ///   - Volume threshold set but volume measurement disabled
    ///   - Time threshold set but duration measurement disabled
    pub fn build(self) -> Result<CreateUrr, PfcpError> {
        // Validate required fields first (without consuming)
        self.urr_id.as_ref().ok_or(PfcpError::MissingMandatoryIe {
            ie_type: IeType::UrrId,
            message_type: None,
            parent_ie: Some(IeType::CreateUrr),
        })?;

        let measurement_method =
            self.measurement_method
                .as_ref()
                .ok_or(PfcpError::MissingMandatoryIe {
                    ie_type: IeType::MeasurementMethod,
                    message_type: None,
                    parent_ie: Some(IeType::CreateUrr),
                })?;

        self.reporting_triggers
            .as_ref()
            .ok_or(PfcpError::MissingMandatoryIe {
                ie_type: IeType::ReportingTriggers,
                message_type: None,
                parent_ie: Some(IeType::CreateUrr),
            })?;

        // Validate measurement method and threshold consistency
        self.validate_measurement_thresholds(measurement_method)?;

        // Now consume the values after validation
        Ok(CreateUrr {
            urr_id: self.urr_id.unwrap(),
            measurement_method: self.measurement_method.unwrap(),
            reporting_triggers: self.reporting_triggers.unwrap(),
            monitoring_time: self.monitoring_time,
            volume_threshold: self.volume_threshold,
            time_threshold: self.time_threshold,
            subsequent_volume_threshold: self.subsequent_volume_threshold,
            subsequent_time_threshold: self.subsequent_time_threshold,
            inactivity_detection_time: self.inactivity_detection_time,
            volume_quota: self.volume_quota,
            time_quota: self.time_quota,
            measurement_period: self.measurement_period,
        })
    }

    /// Validates that measurement method matches the configured thresholds.
    fn validate_measurement_thresholds(
        &self,
        measurement_method: &MeasurementMethod,
    ) -> Result<(), PfcpError> {
        // Validate volume measurement consistency
        if measurement_method.volume {
            if self.volume_threshold.is_none() && self.subsequent_volume_threshold.is_none() {
                return Err(PfcpError::validation_error(
                    "CreateUrrBuilder",
                    "volume_threshold",
                    "Volume measurement enabled but no volume threshold configured",
                ));
            }
        } else {
            // Volume measurement disabled but volume thresholds configured
            if self.volume_threshold.is_some() || self.subsequent_volume_threshold.is_some() {
                return Err(PfcpError::validation_error(
                    "CreateUrrBuilder",
                    "volume_threshold",
                    "Volume threshold configured but volume measurement is disabled",
                ));
            }
        }

        // Validate duration measurement consistency
        if measurement_method.duration {
            if self.time_threshold.is_none() && self.subsequent_time_threshold.is_none() {
                return Err(PfcpError::validation_error(
                    "CreateUrrBuilder",
                    "time_threshold",
                    "Duration measurement enabled but no time threshold configured",
                ));
            }
        } else {
            // Duration measurement disabled but time thresholds configured
            if self.time_threshold.is_some() || self.subsequent_time_threshold.is_some() {
                return Err(PfcpError::validation_error(
                    "CreateUrrBuilder",
                    "time_threshold",
                    "Time threshold configured but duration measurement is disabled",
                ));
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, SystemTime};

    #[test]
    fn test_create_urr_marshal_unmarshal_mandatory() {
        let urr_id = UrrId::new(1);
        let measurement_method = MeasurementMethod::new(true, false, true);
        let reporting_triggers = ReportingTriggers::new();

        let create_urr = CreateUrr::new(
            urr_id,
            measurement_method,
            reporting_triggers,
            None,
            None,
            None,
            None,
            None,
            None,
        );

        let marshaled = create_urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();

        assert_eq!(create_urr, unmarshaled);
    }

    #[test]
    fn test_create_urr_marshal_unmarshal_all() {
        let urr_id = UrrId::new(1);
        let measurement_method = MeasurementMethod::new(true, false, true);
        let reporting_triggers = ReportingTriggers::new();
        let now = SystemTime::now();
        let now_secs = now
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let monitoring_time =
            MonitoringTime::new(SystemTime::UNIX_EPOCH + Duration::from_secs(now_secs));
        let volume_threshold = VolumeThreshold::new(true, true, false, Some(1000), Some(500), None);
        let time_threshold = TimeThreshold::new(3600);
        let subsequent_volume_threshold =
            SubsequentVolumeThreshold::new(false, true, true, None, Some(200), Some(300));
        let subsequent_time_threshold = SubsequentTimeThreshold::new(1800);
        let inactivity_detection_time = InactivityDetectionTime::new(60);

        let create_urr = CreateUrr::new(
            urr_id,
            measurement_method,
            reporting_triggers,
            Some(monitoring_time),
            Some(volume_threshold),
            Some(time_threshold),
            Some(subsequent_volume_threshold),
            Some(subsequent_time_threshold),
            Some(inactivity_detection_time),
        );

        let marshaled = create_urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();

        assert_eq!(create_urr, unmarshaled);
    }

    #[test]
    fn test_builder_basic() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, false, true)) // event only
            .reporting_triggers(ReportingTriggers::new())
            .build()
            .unwrap();

        assert_eq!(urr.urr_id, UrrId::new(1));
        assert!(urr.volume_threshold.is_none());
        assert!(urr.time_threshold.is_none());
    }

    #[test]
    fn test_builder_with_volume_threshold() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume measurement
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000)
            .build()
            .unwrap();

        assert!(urr.volume_threshold.is_some());
        let vt = urr.volume_threshold.unwrap();
        assert_eq!(vt.total_volume, Some(1_000_000_000));
    }

    #[test]
    fn test_builder_with_time_threshold() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false)) // duration measurement
            .reporting_triggers(ReportingTriggers::new())
            .time_threshold_seconds(3600)
            .build()
            .unwrap();

        assert!(urr.time_threshold.is_some());
        let tt = urr.time_threshold.unwrap();
        assert_eq!(tt.value, 3600);
    }

    #[test]
    fn test_builder_comprehensive() {
        let now = SystemTime::now();
        let now_secs = now
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, true, false)) // duration + volume
            .reporting_triggers(ReportingTriggers::new())
            .monitoring_time(MonitoringTime::new(
                SystemTime::UNIX_EPOCH + Duration::from_secs(now_secs),
            ))
            .volume_threshold_bytes(1_000_000_000)
            .time_threshold_seconds(3600)
            .subsequent_volume_threshold_bytes(500_000_000)
            .subsequent_time_threshold_seconds(1800)
            .inactivity_detection_time_seconds(60)
            .build()
            .unwrap();

        assert!(urr.monitoring_time.is_some());
        assert!(urr.volume_threshold.is_some());
        assert!(urr.time_threshold.is_some());
        assert!(urr.subsequent_volume_threshold.is_some());
        assert!(urr.subsequent_time_threshold.is_some());
        assert!(urr.inactivity_detection_time.is_some());
    }

    #[test]
    fn test_builder_uplink_downlink_volume() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume measurement
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_uplink_downlink(500_000_000, 1_000_000_000)
            .build()
            .unwrap();

        let vt = urr.volume_threshold.unwrap();
        assert_eq!(vt.uplink_volume, Some(500_000_000));
        assert_eq!(vt.downlink_volume, Some(1_000_000_000));
        assert_eq!(vt.total_volume, None);
    }

    #[test]
    fn test_builder_missing_measurement_method() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .reporting_triggers(ReportingTriggers::new())
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::MissingMandatoryIe { ie_type, .. } => {
                assert_eq!(ie_type, IeType::MeasurementMethod);
            }
            _ => panic!("Expected MissingMandatoryIe error"),
        }
    }

    #[test]
    fn test_builder_missing_reporting_triggers() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false))
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::MissingMandatoryIe { ie_type, .. } => {
                assert_eq!(ie_type, IeType::ReportingTriggers);
            }
            _ => panic!("Expected MissingMandatoryIe error"),
        }
    }

    #[test]
    fn test_builder_round_trip_marshal() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, true, false)) // duration + volume
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000)
            .time_threshold_seconds(3600)
            .build()
            .unwrap();

        let marshaled = urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();

        assert_eq!(urr, unmarshaled);
    }

    #[test]
    fn test_builder_method() {
        let urr = CreateUrr::builder(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false)) // duration measurement
            .reporting_triggers(ReportingTriggers::new())
            .time_threshold_seconds(3600)
            .build()
            .unwrap();

        assert_eq!(urr.urr_id, UrrId::new(1));
    }

    #[test]
    fn test_builder_ie_round_trip() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume measurement
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000)
            .build()
            .unwrap();

        let ie = urr.to_ie();
        let unmarshaled = CreateUrr::unmarshal(&ie.payload).unwrap();

        assert_eq!(urr, unmarshaled);
    }

    // Type safety validation tests
    #[test]
    fn test_builder_validation_volume_without_threshold() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume enabled
            .reporting_triggers(ReportingTriggers::new())
            // No volume threshold set
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::ValidationError {
                builder,
                field,
                reason,
            } => {
                assert_eq!(builder, "CreateUrrBuilder");
                assert_eq!(field, "volume_threshold");
                assert!(reason.contains("Volume measurement enabled"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_builder_validation_threshold_without_volume() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false)) // duration only, volume disabled
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000) // volume threshold but volume disabled
            .time_threshold_seconds(3600)
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::ValidationError {
                builder,
                field,
                reason,
            } => {
                assert_eq!(builder, "CreateUrrBuilder");
                assert_eq!(field, "volume_threshold");
                assert!(reason.contains("Volume threshold configured"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_builder_validation_duration_without_threshold() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false)) // duration enabled
            .reporting_triggers(ReportingTriggers::new())
            // No time threshold set
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::ValidationError {
                builder,
                field,
                reason,
            } => {
                assert_eq!(builder, "CreateUrrBuilder");
                assert_eq!(field, "time_threshold");
                assert!(reason.contains("Duration measurement enabled"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_builder_validation_threshold_without_duration() {
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume only
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000)
            .time_threshold_seconds(3600) // time threshold but duration disabled
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            PfcpError::ValidationError {
                builder,
                field,
                reason,
            } => {
                assert_eq!(builder, "CreateUrrBuilder");
                assert_eq!(field, "time_threshold");
                assert!(reason.contains("Time threshold configured"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_builder_validation_subsequent_volume_counts() {
        // Subsequent volume threshold should count as volume threshold
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, true, false)) // volume enabled
            .reporting_triggers(ReportingTriggers::new())
            .subsequent_volume_threshold_bytes(500_000_000) // Only subsequent, no initial
            .build();

        // Should succeed - subsequent threshold is valid for volume measurement
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_validation_subsequent_time_counts() {
        // Subsequent time threshold should count as time threshold
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, false, false)) // duration enabled
            .reporting_triggers(ReportingTriggers::new())
            .subsequent_time_threshold_seconds(1800) // Only subsequent, no initial
            .build();

        // Should succeed - subsequent threshold is valid for duration measurement
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_validation_event_only_no_thresholds() {
        // Event measurement doesn't require thresholds
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, false, true)) // event only
            .reporting_triggers(ReportingTriggers::new())
            .build();

        // Should succeed - event measurement doesn't require volume/time thresholds
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_validation_combined_measurements_valid() {
        // Volume + duration measurement with both thresholds
        let result = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(true, true, false))
            .reporting_triggers(ReportingTriggers::new())
            .volume_threshold_bytes(1_000_000_000)
            .time_threshold_seconds(3600)
            .build();

        assert!(result.is_ok());
    }

    #[test]
    fn test_volume_quota_round_trip() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, false, true)) // event
            .reporting_triggers(ReportingTriggers::new())
            .volume_quota_bytes(5_000_000_000)
            .build()
            .unwrap();

        assert!(urr.volume_quota.is_some());
        let marshaled = urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();
        assert_eq!(urr, unmarshaled);
        assert_eq!(
            unmarshaled.volume_quota.unwrap().total_volume,
            Some(5_000_000_000)
        );
    }

    #[test]
    fn test_time_quota_round_trip() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, false, true)) // event
            .reporting_triggers(ReportingTriggers::new())
            .time_quota_seconds(7200)
            .build()
            .unwrap();

        assert!(urr.time_quota.is_some());
        let marshaled = urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();
        assert_eq!(urr, unmarshaled);
        assert_eq!(unmarshaled.time_quota.unwrap().quota_seconds, 7200);
    }

    #[test]
    fn test_measurement_period_round_trip() {
        let urr = CreateUrrBuilder::new(UrrId::new(1))
            .measurement_method(MeasurementMethod::new(false, false, true)) // event
            .reporting_triggers(ReportingTriggers::new())
            .measurement_period_seconds(60)
            .build()
            .unwrap();

        assert!(urr.measurement_period.is_some());
        let marshaled = urr.marshal();
        let unmarshaled = CreateUrr::unmarshal(&marshaled).unwrap();
        assert_eq!(urr, unmarshaled);
        assert_eq!(unmarshaled.measurement_period.unwrap().value, 60);
    }
}