clicksend-rs 0.1.1

Unofficial ClickSend SDK for Rust (async + optional blocking).
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
//! Request and response data types.
//!
//! ClickSend wraps every response in an [`ApiEnvelope`]. Successful calls
//! deserialize into `ApiEnvelope<T>` where `T` is the typed payload.

use serde::{Deserialize, Deserializer, Serialize};

/// Generic ClickSend response envelope. Every endpoint returns this shape.
///
/// The client only returns `Ok(env)` when `response_code == "SUCCESS"` —
/// you do not need to check it manually.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiEnvelope<T> {
    /// HTTP status reflected in the body (usually matches transport status).
    pub http_code: u16,
    /// ClickSend status code (`"SUCCESS"`, `"ERROR"`, `"INVALID_FROM"`, …).
    pub response_code: String,
    /// Human-readable status message.
    #[serde(default)]
    pub response_msg: Option<String>,
    /// Typed payload — `None` only for endpoints that return no data (cancel, etc).
    #[serde(default = "Option::default")]
    pub data: Option<T>,
}

/// Paginated list payload — history, receipts, inbound, etc.
#[derive(Debug, Clone, Deserialize)]
pub struct Paginated<T> {
    /// Total items across all pages.
    #[serde(default)]
    pub total: Option<u64>,
    /// Items per page.
    #[serde(default)]
    pub per_page: Option<u32>,
    /// Current page (1-indexed).
    #[serde(default)]
    pub current_page: Option<u32>,
    /// Last page number.
    #[serde(default)]
    pub last_page: Option<u32>,
    /// URL for the next page, if any.
    #[serde(default)]
    pub next_page_url: Option<String>,
    /// URL for the previous page, if any.
    #[serde(default)]
    pub prev_page_url: Option<String>,
    /// Index of the first item in this page.
    #[serde(default)]
    pub from: Option<u64>,
    /// Index of the last item in this page.
    #[serde(default)]
    pub to: Option<u64>,
    /// Items in the current page.
    #[serde(default = "Vec::new")]
    pub data: Vec<T>,
}

// ───────────────────── helpers ─────────────────────

/// ClickSend returns `schedule` as either a unix timestamp (number) or `""`.
/// Map both into `Option<i64>`: empty string → None, number → Some.
pub(crate) fn deser_schedule<'de, D>(d: D) -> Result<Option<i64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Null => Ok(None),
        serde_json::Value::String(s) if s.is_empty() => Ok(None),
        serde_json::Value::String(s) => s.parse::<i64>().map(Some).map_err(Error::custom),
        serde_json::Value::Number(n) => Ok(n.as_i64()),
        other => Err(Error::custom(format!("invalid schedule field: {other}"))),
    }
}

/// ClickSend frequently returns numeric fields as strings (e.g. `"0.0670"`).
pub(crate) fn deser_str_or_f64<'de, D>(d: D) -> Result<Option<f64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Null => Ok(None),
        serde_json::Value::String(s) if s.is_empty() => Ok(None),
        serde_json::Value::String(s) => s.parse::<f64>().map(Some).map_err(Error::custom),
        serde_json::Value::Number(n) => Ok(n.as_f64()),
        other => Err(Error::custom(format!("expected float-ish, got: {other}"))),
    }
}

// ───────────────────── account ─────────────────────

/// Account info returned by `GET /account`.
///
/// Field names match ClickSend's response verbatim — they prefix things with
/// `user_` (so `user_email`, not `email`). Use [`AccountData::email`] for
/// brevity.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct AccountData {
    /// Numeric user id.
    #[serde(default)]
    pub user_id: Option<u64>,
    /// Username (also your basic-auth username).
    #[serde(default)]
    pub username: Option<String>,
    /// Email on file. See also [`AccountData::email`].
    #[serde(default)]
    pub user_email: Option<String>,
    /// Phone in E.164.
    #[serde(default)]
    pub user_phone: Option<String>,
    /// First name.
    #[serde(default)]
    pub user_first_name: Option<String>,
    /// Last name.
    #[serde(default)]
    pub user_last_name: Option<String>,
    /// `1` if active, `0` if not.
    #[serde(default)]
    pub active: Option<u8>,
    /// `1` if account is banned.
    #[serde(default)]
    pub banned: Option<u8>,
    /// Unix timestamp of sign-up.
    #[serde(default)]
    pub date_sign_up: Option<i64>,
    /// Account balance in [`Currency`] (returned as a string by the API,
    /// parsed into `f64` here).
    #[serde(default, deserialize_with = "deser_str_or_f64")]
    pub balance: Option<f64>,
    /// Display name.
    #[serde(default)]
    pub account_name: Option<String>,
    /// Where invoices go.
    #[serde(default)]
    pub account_billing_email: Option<String>,
    /// Account country (ISO).
    #[serde(default)]
    pub country: Option<String>,
    /// Default country code for SMS without explicit country.
    #[serde(default)]
    pub default_country_sms: Option<String>,
    /// IANA timezone string.
    #[serde(default)]
    pub timezone: Option<String>,
    /// `1` if on a trial plan.
    #[serde(default)]
    pub on_trial: Option<u8>,
    /// Currency block (USD/AUD/EUR/etc).
    #[serde(default, rename = "_currency")]
    pub currency: Option<Currency>,
}

impl AccountData {
    /// Shortcut for [`AccountData::user_email`].
    pub fn email(&self) -> Option<&str> {
        self.user_email.as_deref()
    }
}

// ───────────────────── sms ─────────────────────

/// A single SMS to be sent.
///
/// Build with [`SmsMessage::new`] then chain optional setters. Wrap in
/// [`SmsMessageCollection`] to send.
#[derive(Debug, Clone, Serialize, Default)]
pub struct SmsMessage {
    /// Sender ID — alphanumeric (e.g. `"MyBrand"`) or E.164 number you own.
    /// If `None`, ClickSend picks a shared number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Message text. Long messages get split into parts and billed per part.
    pub body: String,
    /// Recipient in E.164 (`+15551234567`). Either this or [`Self::list_id`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    /// Free-form tag of where this came from (e.g. `"rust"`). Defaults to `"rust"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Unix timestamp for scheduled send. `None` = immediate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<i64>,
    /// Your reference id; echoed back in delivery receipts and replies.
    #[serde(skip_serializing_if = "Option::is_none", rename = "custom_string")]
    pub custom_string: Option<String>,
    /// Send to a saved contact list instead of [`Self::to`].
    #[serde(skip_serializing_if = "Option::is_none", rename = "list_id")]
    pub list_id: Option<i64>,
    /// ISO country (e.g. `"US"`) — improves routing for some numbers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Where replies should be emailed.
    #[serde(skip_serializing_if = "Option::is_none", rename = "from_email")]
    pub from_email: Option<String>,
}

impl SmsMessage {
    /// New SMS with required `to` and `body`. Source defaults to `"rust"`.
    pub fn new(to: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            to: Some(to.into()),
            body: body.into(),
            source: Some("rust".into()),
            ..Default::default()
        }
    }

    /// Set the sender id.
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Schedule for later (unix timestamp).
    pub fn schedule(mut self, ts: i64) -> Self {
        self.schedule = Some(ts);
        self
    }

    /// Tag the message with your own reference.
    pub fn custom_string(mut self, s: impl Into<String>) -> Self {
        self.custom_string = Some(s.into());
        self
    }
}

/// Batch of SMS sent in one API call. Pricing/sending is per-message.
#[derive(Debug, Clone, Serialize)]
pub struct SmsMessageCollection {
    /// The messages to send.
    pub messages: Vec<SmsMessage>,
}

impl SmsMessageCollection {
    /// Wrap a vec of messages.
    pub fn new(messages: Vec<SmsMessage>) -> Self {
        Self { messages }
    }
}

/// Response payload for `/sms/send` and `/sms/price`. Same shape — `price`
/// just doesn't actually send.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SmsSendData {
    /// Sum of `message_price` across all messages. ClickSend returns this
    /// as a string; parsed to `f64` here.
    #[serde(default, deserialize_with = "deser_str_or_f64")]
    pub total_price: Option<f64>,
    /// Total messages submitted.
    #[serde(default)]
    pub total_count: Option<u32>,
    /// Successfully queued for sending.
    #[serde(default)]
    pub queued_count: Option<u32>,
    /// Rejected (blocked sender id, opt-out, etc).
    #[serde(default)]
    pub blocked_count: Option<u32>,
    /// Per-message results in the same order as the request.
    #[serde(default)]
    pub messages: Vec<SmsSendMessageResult>,
    /// Currency block.
    #[serde(default, rename = "_currency")]
    pub currency: Option<Currency>,
}

/// Currency block embedded under `_currency` in many responses.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Currency {
    /// Short code (e.g. `"USD"`).
    #[serde(default)]
    pub currency_name_short: Option<String>,
    /// Long name (e.g. `"US Dollars"`).
    #[serde(default)]
    pub currency_name_long: Option<String>,
    /// Dollar/major prefix (e.g. `"$"`).
    #[serde(default)]
    pub currency_prefix_d: Option<String>,
    /// Cent/minor prefix (e.g. `"¢"`).
    #[serde(default)]
    pub currency_prefix_c: Option<String>,
}

/// One row returned by `/sms/send` and `/sms/price`.
///
/// Most fields are `Option` because `price` doesn't populate post-send fields
/// (`carrier`, `status_code`, …) and `send` doesn't populate response-only
/// fields. Inspect [`Self::status`] to tell what happened to each message.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SmsSendMessageResult {
    /// `"out"` for outbound, `"in"` for inbound replies.
    #[serde(default)]
    pub direction: Option<String>,
    /// Unix timestamp when ClickSend processed the message.
    #[serde(default)]
    pub date: Option<i64>,
    /// Recipient (E.164).
    #[serde(default)]
    pub to: Option<String>,
    /// Message body.
    #[serde(default)]
    pub body: Option<String>,
    /// Sender id used.
    #[serde(default)]
    pub from: Option<String>,
    /// Scheduled send time. Quirky: ClickSend returns `""` for "send now",
    /// or a unix timestamp number — both map to `Option<i64>` here.
    #[serde(default, deserialize_with = "deser_schedule")]
    pub schedule: Option<i64>,
    /// Globally unique message id (use this for cancel/receipts).
    #[serde(default)]
    pub message_id: Option<String>,
    /// SMS parts (long messages get split). Each part is billed.
    #[serde(default)]
    pub message_parts: Option<u32>,
    /// Per-message price. Returned as a string by the API.
    #[serde(default, deserialize_with = "deser_str_or_f64")]
    pub message_price: Option<f64>,
    /// Echoed back from your request.
    #[serde(default)]
    pub custom_string: Option<String>,
    /// Owner user id.
    #[serde(default)]
    pub user_id: Option<u64>,
    /// Subaccount id (multi-tenant accounts).
    #[serde(default)]
    pub subaccount_id: Option<u64>,
    /// Detected destination country (ISO).
    #[serde(default)]
    pub country: Option<String>,
    /// Detected carrier (`"Vodafone"`, `"Verizon"`, …). Populated post-send.
    #[serde(default)]
    pub carrier: Option<String>,
    /// `"SUCCESS"` / `"Sent"` / `"FAILED"` etc.
    #[serde(default)]
    pub status: Option<String>,
    /// Numeric status (per `/sms/history` schema).
    #[serde(default)]
    pub status_code: Option<String>,
    /// Human-readable status.
    #[serde(default)]
    pub status_text: Option<String>,
    /// Numeric error code if delivery failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error.
    #[serde(default)]
    pub error_text: Option<String>,
    /// `true` if a shared sender pool number was used.
    #[serde(default)]
    pub is_shared_system_number: Option<bool>,
}

/// One row in `/sms/history` — a previously sent (or scheduled) message,
/// including its current delivery status.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SmsHistoryItem {
    /// `"out"` for outbound, `"in"` for inbound.
    #[serde(default)]
    pub direction: Option<String>,
    /// Unix timestamp when ClickSend processed it.
    #[serde(default)]
    pub date: Option<i64>,
    /// Recipient.
    #[serde(default)]
    pub to: Option<String>,
    /// Body.
    #[serde(default)]
    pub body: Option<String>,
    /// Sender id used.
    #[serde(default)]
    pub from: Option<String>,
    /// Scheduled time (`""` → None, num → Some).
    #[serde(default, deserialize_with = "deser_schedule")]
    pub schedule: Option<i64>,
    /// Message id.
    #[serde(default)]
    pub message_id: Option<String>,
    /// Number of SMS parts.
    #[serde(default)]
    pub message_parts: Option<u32>,
    /// Price (string in API, parsed here).
    #[serde(default, deserialize_with = "deser_str_or_f64")]
    pub message_price: Option<f64>,
    /// Your reference.
    #[serde(default)]
    pub custom_string: Option<String>,
    /// Owner user id.
    #[serde(default)]
    pub user_id: Option<u64>,
    /// Subaccount id.
    #[serde(default)]
    pub subaccount_id: Option<u64>,
    /// Destination country (ISO).
    #[serde(default)]
    pub country: Option<String>,
    /// Carrier.
    #[serde(default)]
    pub carrier: Option<String>,
    /// Status string.
    #[serde(default)]
    pub status: Option<String>,
    /// Numeric status code.
    #[serde(default)]
    pub status_code: Option<String>,
    /// Human-readable status.
    #[serde(default)]
    pub status_text: Option<String>,
    /// Error code if any.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Error text if any.
    #[serde(default)]
    pub error_text: Option<String>,
}

/// One row in `/sms/receipts` — a delivery confirmation.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SmsReceiptItem {
    /// Message id this receipt is for.
    #[serde(default)]
    pub message_id: Option<String>,
    /// Status string (e.g. `"DELIVERED"`).
    #[serde(default)]
    pub status: Option<String>,
    /// Numeric status code.
    #[serde(default)]
    pub status_code: Option<String>,
    /// Human-readable status.
    #[serde(default)]
    pub status_text: Option<String>,
    /// When the carrier reported delivery.
    #[serde(default)]
    pub timestamp: Option<i64>,
    /// Sender id used.
    #[serde(default)]
    pub originator: Option<String>,
}

/// One row in `/sms/inbound` — an incoming SMS to your numbers.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SmsInboundItem {
    /// Message id assigned by ClickSend.
    #[serde(default)]
    pub message_id: Option<String>,
    /// Who texted you.
    #[serde(default)]
    pub from: Option<String>,
    /// Which of your numbers received it.
    #[serde(default)]
    pub to: Option<String>,
    /// Message body.
    #[serde(default)]
    pub body: Option<String>,
    /// When it arrived.
    #[serde(default)]
    pub timestamp: Option<i64>,
    /// Your reference (echoed from the original outbound).
    #[serde(default)]
    pub custom_string: Option<String>,
    /// If this is a reply, the id of the message it's replying to.
    #[serde(default)]
    pub original_message_id: Option<String>,
    /// Original outbound body (if this is a reply).
    #[serde(default)]
    pub original_body: Option<String>,
    /// Sender id of the original outbound.
    #[serde(default)]
    pub originator: Option<String>,
}

// ───────────────────── mms ─────────────────────

/// One MMS to be sent. Subject has a 20-char limit per ClickSend.
#[derive(Debug, Clone, Serialize, Default)]
pub struct MmsMessage {
    /// Sender id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Message text.
    pub body: String,
    /// Subject (max 20 chars).
    pub subject: String,
    /// Recipient (E.164).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    /// Source tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Unix timestamp for scheduled send.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<i64>,
    /// Your reference id.
    #[serde(skip_serializing_if = "Option::is_none", rename = "custom_string")]
    pub custom_string: Option<String>,
    /// Send to a saved list instead of `to`.
    #[serde(skip_serializing_if = "Option::is_none", rename = "list_id")]
    pub list_id: Option<i64>,
    /// Destination country (ISO).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Where replies should be emailed.
    #[serde(skip_serializing_if = "Option::is_none", rename = "from_email")]
    pub from_email: Option<String>,
}

impl MmsMessage {
    /// New MMS with required `to`, `subject`, `body`. Source defaults to `"rust"`.
    pub fn new(
        to: impl Into<String>,
        subject: impl Into<String>,
        body: impl Into<String>,
    ) -> Self {
        Self {
            to: Some(to.into()),
            subject: subject.into(),
            body: body.into(),
            source: Some("rust".into()),
            ..Default::default()
        }
    }
}

/// Batch of MMS sharing one media URL.
///
/// **Gotcha:** `media_file` must be a publicly reachable URL (PNG/JPG/GIF) —
/// ClickSend pulls it down. There is no upload-from-bytes path here.
#[derive(Debug, Clone, Serialize)]
pub struct MmsMessageCollection {
    /// Public URL to the image.
    pub media_file: String,
    /// Messages to send (all share the same `media_file`).
    pub messages: Vec<MmsMessage>,
}

impl MmsMessageCollection {
    /// Wrap a media URL + messages.
    pub fn new(media_file: impl Into<String>, messages: Vec<MmsMessage>) -> Self {
        Self {
            media_file: media_file.into(),
            messages,
        }
    }
}

// ───────────────────── voice ─────────────────────

/// One TTS voice call.
///
/// ClickSend will dial `to`, then a TTS engine reads `body` aloud in `lang`
/// using the `voice` (`"female"`/`"male"`).
#[derive(Debug, Clone, Serialize, Default)]
pub struct VoiceMessage {
    /// Recipient (E.164).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    /// Text the TTS engine reads aloud.
    pub body: String,
    /// `"female"` or `"male"`.
    pub voice: String,
    /// BCP-47-ish language tag (e.g. `"en-us"`, `"en-gb"`, `"de-de"`).
    pub lang: String,
    /// Destination country (ISO).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Source tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Your reference id.
    #[serde(skip_serializing_if = "Option::is_none", rename = "custom_string")]
    pub custom_string: Option<String>,
    /// Send to a saved list instead of `to`.
    #[serde(skip_serializing_if = "Option::is_none", rename = "list_id")]
    pub list_id: Option<i64>,
    /// Schedule for later (unix timestamp).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<i64>,
    /// `1` to capture a DTMF keypress from the recipient.
    #[serde(skip_serializing_if = "Option::is_none", rename = "require_input")]
    pub require_input: Option<u8>,
    /// `1` to detect voicemail and leave a message.
    #[serde(skip_serializing_if = "Option::is_none", rename = "machine_detection")]
    pub machine_detection: Option<u8>,
}

impl VoiceMessage {
    /// New voice call with required `to` and `body`.
    /// Defaults: voice=female, lang=en-us, source=rust.
    pub fn new(to: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            to: Some(to.into()),
            body: body.into(),
            voice: "female".into(),
            lang: "en-us".into(),
            source: Some("rust".into()),
            ..Default::default()
        }
    }

    /// Override the voice (`"female"` or `"male"`).
    pub fn voice(mut self, v: impl Into<String>) -> Self {
        self.voice = v.into();
        self
    }

    /// Override the language tag.
    pub fn lang(mut self, v: impl Into<String>) -> Self {
        self.lang = v.into();
        self
    }
}

/// Batch of voice calls.
#[derive(Debug, Clone, Serialize)]
pub struct VoiceMessageCollection {
    /// Calls to dial.
    pub messages: Vec<VoiceMessage>,
}

impl VoiceMessageCollection {
    /// Wrap a vec of calls.
    pub fn new(messages: Vec<VoiceMessage>) -> Self {
        Self { messages }
    }
}

// ───────────────────── email ─────────────────────

/// One recipient in `to` / `cc` / `bcc`.
#[derive(Debug, Clone, Serialize)]
pub struct EmailRecipient {
    /// Email address.
    pub email: String,
    /// Display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// `from` block for [`Email`].
///
/// **Major gotcha:** `email_address_id` is **NOT** an email — it is the
/// numeric/string id ClickSend assigns after you register and verify a sender
/// address in the dashboard. Plug in `"hello@you.com"` and it will be rejected.
#[derive(Debug, Clone, Serialize)]
pub struct EmailFrom {
    /// ClickSend's id for a verified sender (NOT an email).
    pub email_address_id: String,
    /// Display name shown in the recipient's inbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// A transactional email payload for `/email/send`.
#[derive(Debug, Clone, Serialize)]
pub struct Email {
    /// Primary recipients.
    pub to: Vec<EmailRecipient>,
    /// CC recipients.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cc: Option<Vec<EmailRecipient>>,
    /// BCC recipients.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<Vec<EmailRecipient>>,
    /// Sender (uses [`EmailFrom::email_address_id`] — see its docs).
    pub from: EmailFrom,
    /// Subject line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// Body. ClickSend treats this as HTML.
    pub body: String,
    /// Attachments. Schema is open-ended — file a PR if you wire it up.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<serde_json::Value>>,
    /// Scheduled send time (unix timestamp).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<i64>,
}

// ───────────────────── webhooks ─────────────────────

/// Body of an **inbound SMS** webhook (ClickSend POSTs this to your URL when a
/// number of yours receives a text). Decode with
/// [`crate::webhook::parse_inbound_sms`].
#[derive(Debug, Clone, Default, Deserialize)]
pub struct InboundSmsWebhook {
    /// Message id.
    #[serde(default)]
    pub message_id: Option<String>,
    /// Sender (the texter).
    #[serde(default)]
    pub from: Option<String>,
    /// Your number that received the text.
    #[serde(default)]
    pub to: Option<String>,
    /// Message body.
    #[serde(default)]
    pub body: Option<String>,
    /// When ClickSend received it.
    #[serde(default)]
    pub timestamp: Option<i64>,
    /// Your reference id (echoed from the original outbound).
    #[serde(default)]
    pub custom_string: Option<String>,
    /// If this is a reply, the id of the message it's replying to.
    #[serde(default)]
    pub original_message_id: Option<String>,
    /// Original outbound body.
    #[serde(default)]
    pub original_body: Option<String>,
    /// Sender id of the original outbound.
    #[serde(default)]
    pub originator: Option<String>,
}

/// Body of a **delivery receipt** webhook. Decode with
/// [`crate::webhook::parse_delivery_receipt`].
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DeliveryReceiptWebhook {
    /// Message id this receipt is for.
    #[serde(default)]
    pub message_id: Option<String>,
    /// Status string (e.g. `"DELIVERED"`).
    #[serde(default)]
    pub status: Option<String>,
    /// Numeric status code.
    #[serde(default)]
    pub status_code: Option<String>,
    /// Human-readable status.
    #[serde(default)]
    pub status_text: Option<String>,
    /// Numeric error code if delivery failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error.
    #[serde(default)]
    pub error_text: Option<String>,
    /// When the carrier reported the result.
    #[serde(default)]
    pub timestamp: Option<i64>,
    /// Your reference id.
    #[serde(default)]
    pub custom_string: Option<String>,
    /// Sender id used for the outbound.
    #[serde(default)]
    pub originator: Option<String>,
}