voip-ms 0.3.0

Async client for the VoIP.ms REST API
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
use rust_decimal::Decimal;
use serde_json::{Value, json};
use voip_ms::{
    ApiStatus, Client, Error, GetBalanceParams, GetSubAccountsParams, GetSubAccountsResponse,
};
use wiremock::matchers::{method, path, query_param, query_param_is_missing};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Build a `Client` pointed at a mock server's REST endpoint.
async fn fixture() -> (MockServer, Client) {
    let server = MockServer::start().await;
    let base_url = format!("{}/api/v1/rest.php", server.uri()).parse().unwrap();
    let client = Client::builder("user@example.com", "secret")
        .base_url(base_url)
        .build()
        .unwrap();
    (server, client)
}

#[tokio::test]
async fn call_success_returns_full_envelope() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("api_username", "user@example.com"))
        .and(query_param("api_password", "secret"))
        .and(query_param("method", "getBalance"))
        .and(query_param("advanced", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "balance": {
                "current_balance": "1.234",
                "spent_total": "0.000"
            }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let resp = client
        .get_balance_raw(&GetBalanceParams {
            advanced: Some(true),
        })
        .await
        .unwrap();

    assert_eq!(resp["status"], "success");
    assert_eq!(resp["balance"]["current_balance"], "1.234");
}

#[tokio::test]
async fn api_status_other_than_success_is_an_error() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(json!({"status": "invalid_credentials"})),
        )
        .mount(&server)
        .await;

    let err = client
        .get_balance_raw(&GetBalanceParams::default())
        .await
        .unwrap_err();

    match err {
        Error::Api(s) => {
            assert_eq!(s, ApiStatus::InvalidCredentials);
            assert_eq!(s.as_str(), "invalid_credentials");
            assert_eq!(s.description(), Some("Username or Password is incorrect"));
            assert!(s.is_documented());
        }
        other => panic!("expected Error::Api, got {other:?}"),
    }
}

#[test]
fn api_status_variants_and_descriptions() {
    // A documented code round-trips to its typed variant and description.
    let status = ApiStatus::from_wire("api_not_enabled");
    assert_eq!(status, ApiStatus::APINotEnabled);
    assert_eq!(status.as_str(), "api_not_enabled");
    assert_eq!(
        status.description(),
        Some("API has not been enabled or has been disabled")
    );
    assert!(status.is_documented());
    assert_eq!(status.to_string(), "api_not_enabled");

    // Acronym-aware variant naming.
    assert_eq!(ApiStatus::from_wire("no_did"), ApiStatus::NoDID);

    // Codes the docs ship capitalized keep their wire casing on the wire
    // side while normalizing to the lowercase-sibling variant form.
    assert_eq!(
        ApiStatus::InvalidThreshold.as_str(),
        "Invalid_threshold",
        "verbatim wire casing is preserved"
    );
    assert_eq!(
        ApiStatus::from_wire("Invalid_threshold"),
        ApiStatus::InvalidThreshold
    );

    // An undocumented code is preserved verbatim with no description.
    let unknown = ApiStatus::from_wire("brand_new_code");
    assert_eq!(unknown, ApiStatus::Unknown("brand_new_code".to_string()));
    assert_eq!(unknown.as_str(), "brand_new_code");
    assert_eq!(unknown.description(), None);
    assert!(!unknown.is_documented());

    // `From<String>`/`From<&str>` keep working against the enum.
    assert_eq!(
        ApiStatus::from("invalid_credentials"),
        ApiStatus::InvalidCredentials
    );

    // Empty-collection statuses are flagged; `no_*` codes that signal a
    // real failure are not.
    assert!(ApiStatus::NoSMS.is_empty());
    assert!(ApiStatus::NoCDR.is_empty());
    assert!(ApiStatus::NoMessages.is_empty());
    assert!(!ApiStatus::NoProvision.is_empty());
    assert!(!ApiStatus::NoBase64file.is_empty());
    assert!(!ApiStatus::NoCallstatus.is_empty());
    assert!(!ApiStatus::InvalidCredentials.is_empty());
    assert!(!ApiStatus::Unknown("whatever".to_string()).is_empty());
}

#[tokio::test]
async fn http_error_status_is_surfaced() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let err = client
        .get_balance_raw(&GetBalanceParams::default())
        .await
        .unwrap_err();

    assert!(matches!(err, Error::Http(_)), "got {err:?}");
}

#[tokio::test]
async fn response_without_status_field_is_invalid() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"unexpected": "shape"})))
        .mount(&server)
        .await;

    let err = client
        .get_balance_raw(&GetBalanceParams::default())
        .await
        .unwrap_err();

    assert!(matches!(err, Error::InvalidResponse(_)), "got {err:?}");
}

#[tokio::test]
async fn omitted_optional_params_are_not_sent() {
    let (server, client) = fixture().await;

    // Match a request that has the credentials + method but NO `advanced` param.
    let mock = Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getBalance"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "success"})))
        .expect(1)
        .mount_as_scoped(&server)
        .await;

    client
        .get_balance_raw(&GetBalanceParams { advanced: None })
        .await
        .unwrap();

    // Drop the scoped mock to verify the expectation.
    let received = server.received_requests().await.unwrap();
    assert_eq!(received.len(), 1);
    let qs = received[0].url.query().unwrap_or_default();
    assert!(
        !qs.contains("advanced="),
        "advanced param should be omitted, query was: {qs}"
    );
    drop(mock);
}

#[tokio::test]
async fn typed_response_via_call_raw_helper() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getBalance"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "balance": {"current_balance": "5.00"}
        })))
        .mount(&server)
        .await;

    #[derive(serde::Deserialize)]
    struct Balance {
        current_balance: String,
    }

    let body: Value = client
        .call_raw("getBalance", &GetBalanceParams::default())
        .await
        .unwrap();

    let balance: Balance = serde_json::from_value(body["balance"].clone()).unwrap();
    assert_eq!(balance.current_balance, "5.00");
}

#[tokio::test]
async fn typed_response_via_call_helper() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getBalance"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "balance": {"current_balance": "7.50"}
        })))
        .mount(&server)
        .await;

    #[derive(serde::Deserialize)]
    struct Envelope {
        balance: Balance,
        status: String,
    }

    #[derive(serde::Deserialize)]
    struct Balance {
        current_balance: String,
    }

    let envelope: Envelope = client
        .call("getBalance", &GetBalanceParams::default())
        .await
        .unwrap();

    assert_eq!(envelope.status, "success");
    assert_eq!(envelope.balance.current_balance, "7.50");
}

#[tokio::test]
async fn typed_response_via_call_at_helper() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getBalance"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "balance": {"current_balance": "9.99"}
        })))
        .mount(&server)
        .await;

    #[derive(serde::Deserialize)]
    struct Balance {
        current_balance: String,
    }

    let balance: Balance = client
        .call_at("getBalance", &GetBalanceParams::default(), "/balance")
        .await
        .unwrap();

    assert_eq!(balance.current_balance, "9.99");
}

#[tokio::test]
async fn typed_response_via_generated_default_method() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getBalance"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "balance": {"current_balance": "12.00"}
        })))
        .mount(&server)
        .await;

    let envelope = client
        .get_balance(&GetBalanceParams::default())
        .await
        .unwrap();

    let current_balance = envelope
        .balance
        .as_ref()
        .and_then(|balance| balance.current_balance);
    assert_eq!(current_balance, Some(Decimal::new(1200, 2)));
}

#[tokio::test]
async fn typed_get_sub_accounts_tolerates_minus_one_sentinel_values() {
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSubAccounts"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "accounts": [
                {
                    "id": "123",
                    "account": "100000_fixture",
                    "username": "fixture-sub",
                    "callerid_number": "-1",
                    "canada_routing": -1
                }
            ]
        })))
        .mount(&server)
        .await;

    let envelope: GetSubAccountsResponse = client
        .get_sub_accounts(&GetSubAccountsParams::default())
        .await
        .unwrap();

    let account = envelope
        .accounts
        .as_ref()
        .and_then(|accounts| accounts.first())
        .expect("expected at least one sub-account");
    assert_eq!(account.id, Some(123));
    assert_eq!(account.callerid_number, None);
    assert_eq!(account.canada_routing, None);
}

#[tokio::test]
async fn typed_get_sub_accounts_decodes_enum_and_routing_fields() {
    use voip_ms::{DtmfMode, Nat};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSubAccounts"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "accounts": [
                {
                    "id": "1",
                    "account": "100000_fixture",
                    "dtmf_mode": "rfc2833",
                    "nat": "route"
                }
            ]
        })))
        .mount(&server)
        .await;

    let envelope: GetSubAccountsResponse = client
        .get_sub_accounts(&GetSubAccountsParams::default())
        .await
        .unwrap();

    let account = envelope
        .accounts
        .as_ref()
        .and_then(|accounts| accounts.first())
        .expect("expected at least one sub-account");

    assert_eq!(account.dtmf_mode, Some(DtmfMode::Rfc2833));
    assert_eq!(account.nat, Some(Nat::Route));
}

#[tokio::test]
async fn routing_param_serializes_as_tagged_string() {
    use voip_ms::{Routing, SetDIDInfoParams};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setDIDInfo"))
        .and(query_param("routing", "account:100001_VoIP"))
        .and(query_param("failover_unreachable", "none:"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = SetDIDInfoParams {
        did: Some("5551234567".into()),
        routing: Some(Routing::Account("100001_VoIP".into())),
        failover_unreachable: Some(Routing::None),
        ..Default::default()
    };
    client.set_did_info_raw(&params).await.unwrap();
}

#[tokio::test]
async fn flag_params_serialize_to_wire_form() {
    // A `1`/`0` flag param is a plain `Option<bool>`; its `serialize_with`
    // emits `1`/`0`, not the `true`/`false` a bare `bool` would produce, which
    // VoIP.ms rejects for these parameters.
    use voip_ms::SetSMSParams;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setSMS"))
        .and(query_param("enable", "1"))
        .and(query_param("email_enabled", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = SetSMSParams {
        did: Some("5551234567".into()),
        enable: Some(true),
        email_enabled: Some(false),
        ..Default::default()
    };
    client.set_sms_raw(&params).await.unwrap();
}

#[tokio::test]
async fn yes_no_flag_param_serializes_to_word() {
    use voip_ms::SetConferenceMemberParams;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setConferenceMember"))
        .and(query_param("admin", "yes"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = SetConferenceMemberParams {
        admin: Some(true),
        ..Default::default()
    };
    client.set_conference_member_raw(&params).await.unwrap();
}

#[tokio::test]
async fn true_only_flag_present_when_true() {
    // `test` is a plain `bool`: `true` serializes `1`, and `false` (the
    // default) is left off the wire entirely.
    use voip_ms::OrderDIDParams;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "orderDID"))
        .and(query_param("test", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = OrderDIDParams {
        test: true,
        ..Default::default()
    };
    client.order_did_raw(&params).await.unwrap();
}

#[tokio::test]
async fn true_only_flag_absent_when_false() {
    use voip_ms::OrderDIDParams;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "orderDID"))
        .and(query_param_is_missing("test"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = OrderDIDParams::default();
    client.order_did_raw(&params).await.unwrap();
}

#[tokio::test]
async fn unknown_enum_value_is_preserved_verbatim() {
    use voip_ms::DtmfMode;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSubAccounts"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "accounts": [
                { "id": "1", "dtmf_mode": "future_mode" }
            ]
        })))
        .mount(&server)
        .await;

    let envelope: GetSubAccountsResponse = client
        .get_sub_accounts(&GetSubAccountsParams::default())
        .await
        .unwrap();
    let account = envelope.accounts.unwrap().into_iter().next().unwrap();
    assert_eq!(
        account.dtmf_mode,
        Some(DtmfMode::Unknown("future_mode".into())),
    );
}

#[tokio::test]
async fn queue_empty_behavior_param_serializes_to_wire() {
    // The third value (`strict`) is why this is an enum, not a bool: a bool
    // would lose it. The param serializes to its bare wire string.
    use voip_ms::{QueueEmptyBehavior, SetQueueParams};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setQueue"))
        .and(query_param("leave_when_empty", "strict"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    let params = SetQueueParams {
        leave_when_empty: Some(QueueEmptyBehavior::Strict),
        ..Default::default()
    };
    client.set_queue_raw(&params).await.unwrap();
}

#[tokio::test]
async fn queue_empty_behavior_response_deserializes_third_value() {
    use voip_ms::QueueEmptyBehavior;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getQueues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "queues": [
                { "queue_name": "support", "leave_when_empty": "strict" }
            ]
        })))
        .mount(&server)
        .await;

    let envelope = client
        .get_queues(&voip_ms::GetQueuesParams::default())
        .await
        .unwrap();
    let queue = envelope.queues.unwrap().into_iter().next().unwrap();
    assert_eq!(queue.leave_when_empty, Some(QueueEmptyBehavior::Strict));
}

#[tokio::test]
async fn per_struct_type_enum_serializes() {
    // The same field name (`type`) is a search mode here and a message
    // direction elsewhere; the per-struct override picks the right enum.
    use voip_ms::{GetSMSParams, MessageType, SearchDIDsUSAParams, SearchType};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "searchDIDsUSA"))
        .and(query_param("type", "starts"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;
    client
        .search_dids_usa_raw(&SearchDIDsUSAParams {
            r#type: Some(SearchType::Starts),
            ..Default::default()
        })
        .await
        .unwrap();

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSMS"))
        .and(query_param("type", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;
    client
        .get_sms_raw(&GetSMSParams {
            r#type: Some(MessageType::Received),
            ..Default::default()
        })
        .await
        .unwrap();
}

#[tokio::test]
async fn message_type_response_deserializes_numeric_wire() {
    // VoIP.ms returns the SMS `type` as a bare JSON number (1 = received,
    // 0 = sent), not a string -- the enum deserializer must tolerate that.
    use voip_ms::MessageType;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSMS"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "sms": [
                { "id": 1, "type": 1 },
                { "id": 2, "type": 0 }
            ]
        })))
        .mount(&server)
        .await;

    let envelope = client
        .get_sms(&voip_ms::GetSMSParams::default())
        .await
        .unwrap();
    let msgs = envelope.sms.unwrap();
    assert_eq!(msgs[0].r#type, Some(MessageType::Received));
    assert_eq!(msgs[1].r#type, Some(MessageType::Sent));
}

#[tokio::test]
async fn empty_collection_status_yields_empty_response() {
    // VoIP.ms answers an empty SMS list with `{"status": "no_sms"}` and no
    // `sms` field. For the typed call that is an empty list, not an error:
    // it succeeds with `sms == None`. The `*_raw` escape hatch keeps the
    // verbatim contract and still surfaces it as `Error::Api`.
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getSMS"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "no_sms" })))
        .mount(&server)
        .await;

    let envelope = client
        .get_sms(&voip_ms::GetSMSParams::default())
        .await
        .unwrap();
    assert_eq!(envelope.status.as_deref(), Some("no_sms"));
    assert!(envelope.sms.is_none());

    let err = client
        .get_sms_raw(&voip_ms::GetSMSParams::default())
        .await
        .unwrap_err();
    assert!(matches!(err, Error::Api(ApiStatus::NoSMS)), "got {err:?}");
}

#[tokio::test]
async fn real_error_no_status_still_errors() {
    // `no_*` codes that signal a genuine failure (rather than an empty list)
    // are still surfaced as `Error::Api`.
    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "no_provision" })))
        .mount(&server)
        .await;

    let err = client
        .e911_provision_raw(&voip_ms::E911ProvisionParams::default())
        .await
        .unwrap_err();
    assert!(
        matches!(err, Error::Api(ApiStatus::NoProvision)),
        "got {err:?}"
    );
}

#[tokio::test]
async fn integer_coded_enum_round_trips() {
    // billing_type is a numeric coded enum on the wire (1 = per minute,
    // 2 = flat); it serializes to the digit and parses back from a number.
    use voip_ms::{DidBillingType, GetDIDsInfoParams, SetDIDBillingTypeParams};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setDIDBillingType"))
        .and(query_param("billing_type", "2"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;
    client
        .set_did_billing_type_raw(&SetDIDBillingTypeParams {
            billing_type: Some(DidBillingType::Flat),
            ..Default::default()
        })
        .await
        .unwrap();

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getDIDsInfo"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "dids": [ { "did": "5551234567", "billing_type": 1 } ]
        })))
        .mount(&server)
        .await;
    let envelope = client
        .get_dids_info(&GetDIDsInfoParams::default())
        .await
        .unwrap();
    let did = envelope.dids.unwrap().into_iter().next().unwrap();
    assert_eq!(did.billing_type, Some(DidBillingType::PerMinute));
}

#[tokio::test]
async fn seconds_param_serializes_value_and_sentinel() {
    // A queue duration is a count of seconds OR a no-limit sentinel that
    // serializes to its documented word (`none` / `unlimited`).
    use voip_ms::{Seconds, SetQueueParams, WaitTime};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "setQueue"))
        .and(query_param("retry_timer", "30"))
        .and(query_param("wrapup_time", "none"))
        .and(query_param("maximum_wait_time", "unlimited"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    client
        .set_queue_raw(&SetQueueParams {
            retry_timer: Some(Seconds::Value(30)),
            wrapup_time: Some(Seconds::Unlimited),
            maximum_wait_time: Some(WaitTime::Unlimited),
            ..Default::default()
        })
        .await
        .unwrap();
}

#[tokio::test]
async fn seconds_response_deserializes_number_and_sentinel() {
    use voip_ms::{Seconds, WaitTime};

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getQueues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "queues": [
                { "queue_name": "q", "retry_timer": 30, "maximum_wait_time": "unlimited" }
            ]
        })))
        .mount(&server)
        .await;

    let envelope = client
        .get_queues(&voip_ms::GetQueuesParams::default())
        .await
        .unwrap();
    let queue = envelope.queues.unwrap().into_iter().next().unwrap();
    assert_eq!(queue.retry_timer, Some(Seconds::Value(30)));
    assert_eq!(queue.maximum_wait_time, Some(WaitTime::Unlimited));
}

#[tokio::test]
async fn fax_message_folder_is_free_text_not_voicemail_enum() {
    // `folder` is a `VoicemailFolder` enum on voicemail methods, but a fax
    // folder is a free-text name (`SENT`/`ALL`/user-created) outside that
    // variant set; `getFaxMessages.folder` must stay a `String` so it
    // serializes verbatim. (Regression: the global `folder` override once
    // mistyped this as `VoicemailFolder`.)
    use voip_ms::GetFAXMessagesParams;

    let (server, client) = fixture().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/rest.php"))
        .and(query_param("method", "getFaxMessages"))
        .and(query_param("folder", "SENT"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "status": "success" })))
        .expect(1)
        .mount(&server)
        .await;

    client
        .get_fax_messages_raw(&GetFAXMessagesParams {
            folder: Some("SENT".into()),
            ..Default::default()
        })
        .await
        .unwrap();
}