nylas-types 0.1.1

Type definitions for Nylas API v3
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
//! Message types for the Nylas API v3.

use serde::{Deserialize, Serialize};

use crate::{Attachment, EmailAddress, FolderId, GrantId, MessageId, ThreadId, TrackingOptions};
use std::fmt;

/// Schedule ID for scheduled messages.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ScheduleId(String);

impl ScheduleId {
    /// Create a new schedule ID.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Get the schedule ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ScheduleId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for ScheduleId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for ScheduleId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Email header from a message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailHeader {
    /// Header name (e.g., "X-Custom-Header").
    pub name: String,

    /// Header value.
    pub value: String,
}

/// A message object from the Nylas API.
///
/// Messages are email messages in a user's mailbox.
///
/// # Example
///
/// ```
/// # use nylas_types::{Message, MessageId, GrantId, ThreadId};
/// let message = Message {
///     id: MessageId::new("msg_123"),
///     grant_id: GrantId::new("grant_123"),
///     thread_id: Some(ThreadId::new("thread_123")),
///     subject: Some("Hello".to_string()),
///     from: vec![],
///     to: vec![],
///     cc: vec![],
///     bcc: vec![],
///     reply_to: vec![],
///     date: 1234567890,
///     unread: Some(false),
///     starred: Some(false),
///     snippet: Some("Message snippet...".to_string()),
///     body: Some("Message body".to_string()),
///     attachments: vec![],
///     folders: vec![],
///     created_at: Some(1234567890),
///     headers: None,
///     raw_mime: None,
///     bounce_detected: None,
///     schedule_id: None,
///     send_at: None,
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Message {
    /// Unique identifier for the message.
    pub id: MessageId,

    /// Grant ID associated with this message.
    pub grant_id: GrantId,

    /// Thread ID this message belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<ThreadId>,

    /// Subject line of the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Sender email address(es).
    #[serde(default)]
    pub from: Vec<EmailAddress>,

    /// Recipient email address(es).
    #[serde(default)]
    pub to: Vec<EmailAddress>,

    /// CC recipient email address(es).
    #[serde(default)]
    pub cc: Vec<EmailAddress>,

    /// BCC recipient email address(es).
    #[serde(default)]
    pub bcc: Vec<EmailAddress>,

    /// Reply-to email address(es).
    #[serde(default)]
    pub reply_to: Vec<EmailAddress>,

    /// Unix timestamp when the message was sent/received.
    pub date: i64,

    /// Whether the message is unread.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unread: Option<bool>,

    /// Whether the message is starred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starred: Option<bool>,

    /// Short snippet of the message body.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snippet: Option<String>,

    /// Full body of the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Attachments included with the message.
    #[serde(default)]
    pub attachments: Vec<Attachment>,

    /// Folder IDs this message belongs to.
    #[serde(default)]
    pub folders: Vec<FolderId>,

    /// Unix timestamp when the message was created.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    /// Email headers (returned when fields=include_headers is specified).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<Vec<EmailHeader>>,

    /// Raw MIME data (Base64url-encoded, returned when fields=raw_mime is specified).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_mime: Option<String>,

    /// Whether bounce was detected for this message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bounce_detected: Option<bool>,

    /// Schedule ID if this message is scheduled to be sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule_id: Option<ScheduleId>,

    /// Scheduled send time (Unix timestamp) if this message is scheduled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_at: Option<i64>,
}

/// Query parameters for listing messages.
///
/// # Example
///
/// ```
/// # use nylas_types::MessageQueryParams;
/// let params = MessageQueryParams::builder()
///     .subject("invoice")
///     .unread(true)
///     .limit(50)
///     .build();
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct MessageQueryParams {
    /// Filter by subject (substring match).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Filter by sender email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,

    /// Filter by recipient email (to field).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,

    /// Filter by CC recipient email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cc: Option<String>,

    /// Filter by BCC recipient email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<String>,

    /// Filter by any email (to, from, cc, bcc).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub any_email: Option<String>,

    /// Filter by thread ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,

    /// Filter by unread status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unread: Option<bool>,

    /// Filter by starred status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starred: Option<bool>,

    /// Filter by messages with attachments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_attachment: Option<bool>,

    /// Filter messages received before this timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub received_before: Option<i64>,

    /// Filter messages received after this timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub received_after: Option<i64>,

    /// Filter by folder ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_: Option<String>,

    /// Maximum number of results to return.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,

    /// Page token for pagination.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,

    /// IMAP-specific search query.
    ///
    /// Uses IMAP SEARCH syntax. Only works with IMAP providers.
    ///
    /// # Example
    ///
    /// ```
    /// use nylas_types::MessageQueryParams;
    ///
    /// let params = MessageQueryParams::builder()
    ///     .query_imap("FROM \"sender@example.com\" SUBJECT \"invoice\"")
    ///     .build();
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_imap: Option<String>,
}

impl MessageQueryParams {
    /// Create a new builder for message query parameters.
    pub fn builder() -> MessageQueryParamsBuilder {
        MessageQueryParamsBuilder::default()
    }
}

/// Builder for message query parameters.
#[derive(Debug, Clone, Default)]
pub struct MessageQueryParamsBuilder {
    params: MessageQueryParams,
}

impl MessageQueryParamsBuilder {
    /// Filter by subject (substring match).
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.params.subject = Some(subject.into());
        self
    }

    /// Filter by sender email.
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.params.from = Some(from.into());
        self
    }

    /// Filter by recipient email (to field).
    pub fn to(mut self, to: impl Into<String>) -> Self {
        self.params.to = Some(to.into());
        self
    }

    /// Filter by CC recipient email.
    pub fn cc(mut self, cc: impl Into<String>) -> Self {
        self.params.cc = Some(cc.into());
        self
    }

    /// Filter by BCC recipient email.
    pub fn bcc(mut self, bcc: impl Into<String>) -> Self {
        self.params.bcc = Some(bcc.into());
        self
    }

    /// Filter by any email (to, from, cc, bcc).
    pub fn any_email(mut self, email: impl Into<String>) -> Self {
        self.params.any_email = Some(email.into());
        self
    }

    /// Filter by thread ID.
    pub fn thread_id(mut self, thread_id: impl Into<String>) -> Self {
        self.params.thread_id = Some(thread_id.into());
        self
    }

    /// Filter by unread status.
    pub fn unread(mut self, unread: bool) -> Self {
        self.params.unread = Some(unread);
        self
    }

    /// Filter by starred status.
    pub fn starred(mut self, starred: bool) -> Self {
        self.params.starred = Some(starred);
        self
    }

    /// Filter by messages with attachments.
    pub fn has_attachment(mut self, has_attachment: bool) -> Self {
        self.params.has_attachment = Some(has_attachment);
        self
    }

    /// Filter messages received before this timestamp.
    pub fn received_before(mut self, timestamp: i64) -> Self {
        self.params.received_before = Some(timestamp);
        self
    }

    /// Filter messages received after this timestamp.
    pub fn received_after(mut self, timestamp: i64) -> Self {
        self.params.received_after = Some(timestamp);
        self
    }

    /// Filter by folder ID.
    pub fn in_folder(mut self, folder_id: impl Into<String>) -> Self {
        self.params.in_ = Some(folder_id.into());
        self
    }

    /// Maximum number of results to return.
    pub fn limit(mut self, limit: u32) -> Self {
        self.params.limit = Some(limit);
        self
    }

    /// Page token for pagination.
    pub fn page_token(mut self, token: impl Into<String>) -> Self {
        self.params.page_token = Some(token.into());
        self
    }

    /// Set IMAP-specific search query.
    ///
    /// Uses IMAP SEARCH syntax. Only works with IMAP providers.
    ///
    /// # Arguments
    ///
    /// * `query` - IMAP SEARCH query string
    ///
    /// # Example
    ///
    /// ```
    /// use nylas_types::MessageQueryParams;
    ///
    /// let params = MessageQueryParams::builder()
    ///     .query_imap("UNSEEN FROM \"boss@company.com\"")
    ///     .limit(50)
    ///     .build();
    /// ```
    pub fn query_imap(mut self, query: impl Into<String>) -> Self {
        self.params.query_imap = Some(query.into());
        self
    }

    /// Build the query parameters.
    pub fn build(self) -> MessageQueryParams {
        self.params
    }
}

/// Request to update a message.
///
/// # Example
///
/// ```
/// # use nylas_types::UpdateMessageRequest;
/// let update = UpdateMessageRequest::builder()
///     .unread(false)
///     .starred(true)
///     .build();
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateMessageRequest {
    /// Mark message as read/unread.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unread: Option<bool>,

    /// Mark message as starred/unstarred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starred: Option<bool>,

    /// Update folders the message belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub folders: Option<Vec<String>>,
}

impl UpdateMessageRequest {
    /// Create a new builder for update message request.
    pub fn builder() -> UpdateMessageRequestBuilder {
        UpdateMessageRequestBuilder::default()
    }
}

/// Builder for update message request.
#[derive(Debug, Clone, Default)]
pub struct UpdateMessageRequestBuilder {
    request: UpdateMessageRequest,
}

impl UpdateMessageRequestBuilder {
    /// Mark message as read/unread.
    pub fn unread(mut self, unread: bool) -> Self {
        self.request.unread = Some(unread);
        self
    }

    /// Mark message as starred/unstarred.
    pub fn starred(mut self, starred: bool) -> Self {
        self.request.starred = Some(starred);
        self
    }

    /// Update folders the message belongs to.
    pub fn folders(mut self, folders: Vec<String>) -> Self {
        self.request.folders = Some(folders);
        self
    }

    /// Build the update request.
    pub fn build(self) -> UpdateMessageRequest {
        self.request
    }
}

/// Request to send a new message.
///
/// # Example
///
/// ```
/// # use nylas_types::SendMessageRequest;
/// let request = SendMessageRequest::builder()
///     .subject("Hello")
///     .body("Message body")
///     .to(vec!["recipient@example.com".to_string()])
///     .build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SendMessageRequest {
    /// Message subject.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Message body (plain text or HTML).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Recipient email addresses.
    #[serde(default)]
    pub to: Vec<String>,

    /// CC recipient email addresses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cc: Vec<String>,

    /// BCC recipient email addresses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bcc: Vec<String>,

    /// Reply-to email addresses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reply_to: Vec<String>,

    /// Attachment IDs to include.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<String>,

    /// Unix timestamp to send the message (scheduled send).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_at: Option<i64>,

    /// Tracking options for this message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tracking_options: Option<TrackingOptions>,

    /// Reply to message ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_to_message_id: Option<String>,
}

impl SendMessageRequest {
    /// Create a new builder for send message request.
    pub fn builder() -> SendMessageRequestBuilder {
        SendMessageRequestBuilder::default()
    }
}

/// Builder for send message request.
#[derive(Debug, Clone, Default)]
pub struct SendMessageRequestBuilder {
    request: SendMessageRequest,
}

impl SendMessageRequestBuilder {
    /// Set the message subject.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.request.subject = Some(subject.into());
        self
    }

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

    /// Set recipient email addresses.
    pub fn to(mut self, to: Vec<String>) -> Self {
        self.request.to = to;
        self
    }

    /// Add a single recipient email address.
    pub fn add_to(mut self, to: impl Into<String>) -> Self {
        self.request.to.push(to.into());
        self
    }

    /// Set CC recipient email addresses.
    pub fn cc(mut self, cc: Vec<String>) -> Self {
        self.request.cc = cc;
        self
    }

    /// Add a single CC recipient email address.
    pub fn add_cc(mut self, cc: impl Into<String>) -> Self {
        self.request.cc.push(cc.into());
        self
    }

    /// Set BCC recipient email addresses.
    pub fn bcc(mut self, bcc: Vec<String>) -> Self {
        self.request.bcc = bcc;
        self
    }

    /// Add a single BCC recipient email address.
    pub fn add_bcc(mut self, bcc: impl Into<String>) -> Self {
        self.request.bcc.push(bcc.into());
        self
    }

    /// Set reply-to email addresses.
    pub fn reply_to(mut self, reply_to: Vec<String>) -> Self {
        self.request.reply_to = reply_to;
        self
    }

    /// Set attachment IDs.
    pub fn attachments(mut self, attachments: Vec<String>) -> Self {
        self.request.attachments = attachments;
        self
    }

    /// Add a single attachment ID.
    pub fn add_attachment(mut self, attachment_id: impl Into<String>) -> Self {
        self.request.attachments.push(attachment_id.into());
        self
    }

    /// Set scheduled send time (Unix timestamp).
    pub fn send_at(mut self, timestamp: i64) -> Self {
        self.request.send_at = Some(timestamp);
        self
    }

    /// Set tracking options.
    pub fn tracking(mut self, tracking: TrackingOptions) -> Self {
        self.request.tracking_options = Some(tracking);
        self
    }

    /// Set reply to message ID.
    pub fn reply_to_message_id(mut self, message_id: impl Into<String>) -> Self {
        self.request.reply_to_message_id = Some(message_id.into());
        self
    }

    /// Build the send message request.
    pub fn build(self) -> SendMessageRequest {
        self.request
    }
}

/// Request to clean message bodies.
///
/// Removes quoted text, signatures, and other non-essential content.
///
/// # Example
///
/// ```
/// # use nylas_types::CleanMessagesRequest;
/// let request = CleanMessagesRequest::builder()
///     .message_ids(vec!["msg_1".to_string(), "msg_2".to_string()])
///     .ignore_links(true)
///     .build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CleanMessagesRequest {
    /// Message IDs to clean.
    pub message_ids: Vec<String>,

    /// Remove quoted text from previous emails.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignore_quotes: Option<bool>,

    /// Remove links from the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignore_links: Option<bool>,

    /// Remove images from the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignore_images: Option<bool>,

    /// Remove tables from the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignore_tables: Option<bool>,
}

impl CleanMessagesRequest {
    /// Create a new builder for clean messages request.
    pub fn builder() -> CleanMessagesRequestBuilder {
        CleanMessagesRequestBuilder::default()
    }
}

/// Builder for clean messages request.
#[derive(Debug, Clone, Default)]
pub struct CleanMessagesRequestBuilder {
    message_ids: Vec<String>,
    ignore_quotes: Option<bool>,
    ignore_links: Option<bool>,
    ignore_images: Option<bool>,
    ignore_tables: Option<bool>,
}

impl CleanMessagesRequestBuilder {
    /// Set message IDs to clean.
    pub fn message_ids(mut self, message_ids: Vec<String>) -> Self {
        self.message_ids = message_ids;
        self
    }

    /// Add a single message ID.
    pub fn add_message_id(mut self, message_id: impl Into<String>) -> Self {
        self.message_ids.push(message_id.into());
        self
    }

    /// Set whether to ignore quotes.
    pub fn ignore_quotes(mut self, ignore: bool) -> Self {
        self.ignore_quotes = Some(ignore);
        self
    }

    /// Set whether to ignore links.
    pub fn ignore_links(mut self, ignore: bool) -> Self {
        self.ignore_links = Some(ignore);
        self
    }

    /// Set whether to ignore images.
    pub fn ignore_images(mut self, ignore: bool) -> Self {
        self.ignore_images = Some(ignore);
        self
    }

    /// Set whether to ignore tables.
    pub fn ignore_tables(mut self, ignore: bool) -> Self {
        self.ignore_tables = Some(ignore);
        self
    }

    /// Build the clean messages request.
    pub fn build(self) -> CleanMessagesRequest {
        CleanMessagesRequest {
            message_ids: self.message_ids,
            ignore_quotes: self.ignore_quotes,
            ignore_links: self.ignore_links,
            ignore_images: self.ignore_images,
            ignore_tables: self.ignore_tables,
        }
    }
}

/// Response from clean messages API.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CleanMessagesResponse {
    /// Cleaned message bodies indexed by message ID.
    pub cleaned: std::collections::HashMap<String, String>,
}

/// Response from clean single message endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CleanMessageResponse {
    /// Message ID.
    #[serde(rename = "id")]
    pub message_id: MessageId,

    /// Cleaned conversation text (signature and quotes removed).
    pub conversation: String,
}

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

    #[test]
    fn test_message_creation() {
        let message = Message {
            id: MessageId::new("msg_123"),
            grant_id: GrantId::new("grant_123"),
            thread_id: Some(ThreadId::new("thread_123")),
            subject: Some("Test Subject".to_string()),
            from: vec![],
            to: vec![],
            cc: vec![],
            bcc: vec![],
            reply_to: vec![],
            date: 1234567890,
            unread: Some(true),
            starred: Some(false),
            snippet: Some("Test snippet".to_string()),
            body: Some("Test body".to_string()),
            attachments: vec![],
            folders: vec![],
            created_at: Some(1234567890),
            headers: None,
            raw_mime: None,
            bounce_detected: None,
            schedule_id: None,
            send_at: None,
        };

        assert_eq!(message.id.as_str(), "msg_123");
        assert_eq!(message.grant_id.as_str(), "grant_123");
        assert_eq!(message.subject, Some("Test Subject".to_string()));
        assert_eq!(message.unread, Some(true));
    }

    #[test]
    fn test_message_serialization() {
        let message = Message {
            id: MessageId::new("msg_123"),
            grant_id: GrantId::new("grant_123"),
            thread_id: Some(ThreadId::new("thread_123")),
            subject: Some("Test".to_string()),
            from: vec![],
            to: vec![],
            cc: vec![],
            bcc: vec![],
            reply_to: vec![],
            date: 1234567890,
            unread: Some(true),
            starred: Some(false),
            snippet: Some("Snippet".to_string()),
            body: Some("Body".to_string()),
            attachments: vec![],
            folders: vec![],
            created_at: Some(1234567890),
            headers: None,
            raw_mime: None,
            bounce_detected: None,
            schedule_id: None,
            send_at: None,
        };

        let json = serde_json::to_string(&message).unwrap();
        assert!(json.contains("msg_123"));
        assert!(json.contains("grant_123"));
        assert!(json.contains("Test"));

        let deserialized: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, message);
    }

    #[test]
    fn test_query_params_builder() {
        let params = MessageQueryParams::builder()
            .subject("invoice")
            .unread(true)
            .limit(50)
            .build();

        assert_eq!(params.subject, Some("invoice".to_string()));
        assert_eq!(params.unread, Some(true));
        assert_eq!(params.limit, Some(50));
    }

    #[test]
    fn test_query_params_all_fields() {
        let params = MessageQueryParams::builder()
            .subject("test")
            .from("sender@example.com")
            .to("recipient@example.com")
            .cc("cc@example.com")
            .bcc("bcc@example.com")
            .any_email("any@example.com")
            .thread_id("thread_123")
            .unread(true)
            .starred(false)
            .has_attachment(true)
            .received_before(2000000000)
            .received_after(1000000000)
            .in_folder("folder_123")
            .limit(100)
            .page_token("token_abc")
            .build();

        assert_eq!(params.subject, Some("test".to_string()));
        assert_eq!(params.from, Some("sender@example.com".to_string()));
        assert_eq!(params.to, Some("recipient@example.com".to_string()));
        assert_eq!(params.limit, Some(100));
        assert_eq!(params.page_token, Some("token_abc".to_string()));
    }

    #[test]
    fn test_query_params_serialization() {
        let params = MessageQueryParams::builder()
            .subject("test")
            .unread(true)
            .limit(50)
            .build();

        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("test"));
        assert!(json.contains("true"));
        assert!(json.contains("50"));
    }

    #[test]
    fn test_update_message_request_builder() {
        let update = UpdateMessageRequest::builder()
            .unread(false)
            .starred(true)
            .build();

        assert_eq!(update.unread, Some(false));
        assert_eq!(update.starred, Some(true));
    }

    #[test]
    fn test_update_message_request_with_folders() {
        let update = UpdateMessageRequest::builder()
            .unread(false)
            .folders(vec!["folder1".to_string(), "folder2".to_string()])
            .build();

        assert_eq!(update.unread, Some(false));
        assert_eq!(
            update.folders,
            Some(vec!["folder1".to_string(), "folder2".to_string()])
        );
    }

    #[test]
    fn test_update_message_request_serialization() {
        let update = UpdateMessageRequest::builder()
            .unread(false)
            .starred(true)
            .build();

        let json = serde_json::to_string(&update).unwrap();
        let deserialized: UpdateMessageRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, update);
    }

    #[test]
    fn test_send_message_request_builder() {
        let request = SendMessageRequest::builder()
            .subject("Test Subject")
            .body("Test Body")
            .to(vec!["recipient@example.com".to_string()])
            .build();

        assert_eq!(request.subject, Some("Test Subject".to_string()));
        assert_eq!(request.body, Some("Test Body".to_string()));
        assert_eq!(request.to, vec!["recipient@example.com".to_string()]);
    }

    #[test]
    fn test_send_message_request_with_scheduled_send() {
        let send_time = 1735689600; // 2025-01-01 00:00:00 UTC
        let request = SendMessageRequest::builder()
            .subject("Scheduled Email")
            .body("This will be sent later")
            .to(vec!["recipient@example.com".to_string()])
            .send_at(send_time)
            .build();

        assert_eq!(request.send_at, Some(send_time));
    }

    #[test]
    fn test_send_message_request_with_tracking() {
        let tracking = TrackingOptions::all_enabled();
        let request = SendMessageRequest::builder()
            .subject("Tracked Email")
            .body("This will track opens and clicks")
            .to(vec!["recipient@example.com".to_string()])
            .tracking(tracking.clone())
            .build();

        assert_eq!(request.tracking_options, Some(tracking));
    }

    #[test]
    fn test_clean_messages_request() {
        let request = CleanMessagesRequest::builder()
            .message_ids(vec!["msg_1".to_string(), "msg_2".to_string()])
            .ignore_links(true)
            .ignore_images(false)
            .build();

        assert_eq!(request.message_ids.len(), 2);
        assert_eq!(request.ignore_links, Some(true));
        assert_eq!(request.ignore_images, Some(false));
    }

    #[test]
    fn test_schedule_id_creation() {
        let schedule_id = ScheduleId::new("schedule_123");
        assert_eq!(schedule_id.as_str(), "schedule_123");
    }

    #[test]
    fn test_schedule_id_from_string() {
        let schedule_id: ScheduleId = "schedule_456".into();
        assert_eq!(schedule_id.as_str(), "schedule_456");
    }

    #[test]
    fn test_schedule_id_display() {
        let schedule_id = ScheduleId::new("schedule_789");
        assert_eq!(format!("{}", schedule_id), "schedule_789");
    }

    #[test]
    fn test_email_header_serialization() {
        let header = EmailHeader {
            name: "X-Custom-Header".to_string(),
            value: "custom-value".to_string(),
        };

        let json = serde_json::to_string(&header).unwrap();
        assert!(json.contains("X-Custom-Header"));
        assert!(json.contains("custom-value"));

        let deserialized: EmailHeader = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.name, "X-Custom-Header");
        assert_eq!(deserialized.value, "custom-value");
    }

    #[test]
    fn test_clean_message_response_deserialization() {
        let json = r#"{"id":"msg_123","conversation":"Clean text here"}"#;
        let response: CleanMessageResponse = serde_json::from_str(json).unwrap();

        assert_eq!(response.message_id.as_str(), "msg_123");
        assert_eq!(response.conversation, "Clean text here");
    }

    #[test]
    fn test_message_with_headers() {
        let headers = vec![
            EmailHeader {
                name: "From".to_string(),
                value: "sender@example.com".to_string(),
            },
            EmailHeader {
                name: "Subject".to_string(),
                value: "Test Email".to_string(),
            },
        ];

        let message = Message {
            id: MessageId::new("msg_123"),
            grant_id: GrantId::new("grant_123"),
            thread_id: None,
            subject: Some("Test".to_string()),
            from: vec![],
            to: vec![],
            cc: vec![],
            bcc: vec![],
            reply_to: vec![],
            date: 1234567890,
            unread: None,
            starred: None,
            snippet: None,
            body: None,
            attachments: vec![],
            folders: vec![],
            created_at: None,
            headers: Some(headers.clone()),
            raw_mime: None,
            bounce_detected: None,
            schedule_id: None,
            send_at: None,
        };

        assert!(message.headers.is_some());
        let msg_headers = message.headers.unwrap();
        assert_eq!(msg_headers.len(), 2);
        assert_eq!(msg_headers[0].name, "From");
        assert_eq!(msg_headers[1].name, "Subject");
    }

    #[test]
    fn test_message_with_bounce_detected() {
        let message = Message {
            id: MessageId::new("msg_123"),
            grant_id: GrantId::new("grant_123"),
            thread_id: None,
            subject: Some("Bounced".to_string()),
            from: vec![],
            to: vec![],
            cc: vec![],
            bcc: vec![],
            reply_to: vec![],
            date: 1234567890,
            unread: None,
            starred: None,
            snippet: None,
            body: None,
            attachments: vec![],
            folders: vec![],
            created_at: None,
            headers: None,
            raw_mime: None,
            bounce_detected: Some(true),
            schedule_id: None,
            send_at: None,
        };

        assert_eq!(message.bounce_detected, Some(true));
    }

    #[test]
    fn test_message_with_schedule_id() {
        let message = Message {
            id: MessageId::new("msg_123"),
            grant_id: GrantId::new("grant_123"),
            thread_id: None,
            subject: Some("Scheduled".to_string()),
            from: vec![],
            to: vec![],
            cc: vec![],
            bcc: vec![],
            reply_to: vec![],
            date: 1234567890,
            unread: None,
            starred: None,
            snippet: None,
            body: None,
            attachments: vec![],
            folders: vec![],
            created_at: None,
            headers: None,
            raw_mime: None,
            bounce_detected: None,
            schedule_id: Some(ScheduleId::new("schedule_123")),
            send_at: Some(1735776000),
        };

        assert!(message.schedule_id.is_some());
        assert_eq!(message.schedule_id.unwrap().as_str(), "schedule_123");
        assert_eq!(message.send_at, Some(1735776000));
    }

    #[test]
    fn test_query_imap_parameter() {
        let params = MessageQueryParams::builder()
            .query_imap("FROM \"test@example.com\"")
            .build();

        assert_eq!(
            params.query_imap,
            Some("FROM \"test@example.com\"".to_string())
        );
    }

    #[test]
    fn test_query_imap_serialization() {
        let params = MessageQueryParams {
            query_imap: Some("UNSEEN SUBJECT \"urgent\"".to_string()),
            ..Default::default()
        };

        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("query_imap"));
        assert!(json.contains("UNSEEN SUBJECT"));
    }
}