resend-rs 0.24.0

Resend's Official Rust SDK.
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
use std::fmt;
use std::sync::Arc;

use reqwest::Method;

use crate::{
    Config, Result,
    contacts::types::ContactPropertyChanges,
    list_opts::ListOptions,
    types::{
        AddContactSegmentResponse, ContactProperty, ContactTopic, CreateContactPropertyOptions,
        CreateContactPropertyResponse, DeleteContactPropertyResponse, RemoveContactSegmentResponse,
        Segment, UpdateContactPropertyResponse, UpdateContactTopicOptions,
    },
};
use crate::{
    list_opts::ListResponse,
    types::{Contact, ContactChanges, ContactId, CreateContactOptions},
};

use self::types::UpdateContactResponse;

/// `Resend` APIs for `/audiences/:id/contacts` endpoints.
#[derive(Clone)]
pub struct ContactsSvc(pub(crate) Arc<Config>);

impl ContactsSvc {
    /// Create a contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/create-contact>
    #[maybe_async::maybe_async]
    // Reasoning for allow: https://github.com/resend/resend-rust/pull/1#issuecomment-2081646115
    #[allow(clippy::needless_pass_by_value)]
    pub async fn create(&self, contact: CreateContactOptions) -> Result<ContactId> {
        let path = contact.audience_id.as_ref().map_or_else(
            || "/contacts".to_string(),
            |audience_id| format!("/audiences/{audience_id}/contacts"),
        );

        let request = self.0.build(Method::POST, &path);
        let response = self.0.send(request.json(&contact)).await?;
        let content = response.json::<types::CreateContactResponse>().await?;

        Ok(content.id)
    }

    /// Retrieve a single contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/get-contact>
    #[maybe_async::maybe_async]
    pub async fn get(&self, contact_id_or_email: &str) -> Result<Contact> {
        let path = format!("/contacts/{contact_id_or_email}");

        let request = self.0.build(Method::GET, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<Contact>().await?;

        Ok(content)
    }

    /// Update an existing contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/update-contact>
    #[maybe_async::maybe_async]
    // Reasoning for allow: https://github.com/resend/resend-rust/pull/1#issuecomment-2081646115
    #[allow(clippy::needless_pass_by_value)]
    pub async fn update(
        &self,
        contact_id_or_email: &str,
        update: ContactChanges,
    ) -> Result<UpdateContactResponse> {
        let path = format!("/contacts/{contact_id_or_email}");

        let request = self.0.build(Method::PATCH, &path);
        let response = self.0.send(request.json(&update)).await?;
        let content = response.json::<UpdateContactResponse>().await?;

        Ok(content)
    }

    /// Remove an existing contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/delete-contact>
    #[maybe_async::maybe_async]
    pub async fn delete(&self, contact_id_or_email: &str) -> Result<bool> {
        let path = format!("/contacts/{contact_id_or_email}");

        let request = self.0.build(Method::DELETE, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<types::DeleteContactResponse>().await?;

        Ok(content.deleted)
    }

    /// Retrieves a list contacts from an audience.
    ///
    /// - Default limit: no limit (return everything)
    ///
    /// <https://resend.com/docs/api-reference/contacts/list-contacts>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn list<T>(
        &self,
        audience: &str,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<Contact>> {
        let path = format!("/audiences/{audience}/contacts");

        let request = self.0.build(Method::GET, &path).query(&list_opts);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<Contact>>().await?;

        Ok(content)
    }

    /// Retrieve a list of topics subscriptions for a contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/get-contact-topic>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn get_contact_topics<T>(
        &self,
        contact_id_or_email: &str,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<ContactTopic>> {
        let path = format!("/contacts/{contact_id_or_email}/topics");

        let request = self.0.build(Method::GET, &path).query(&list_opts);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<ContactTopic>>().await?;

        Ok(content)
    }

    /// Update an existing topic subscription for a contact.
    ///
    /// <https://resend.com/docs/api-reference/contacts/update-contact-topic>
    #[maybe_async::maybe_async]
    pub async fn update_contact_topics(
        &self,
        contact_id_or_email: &str,
        topics: impl Into<Vec<UpdateContactTopicOptions>>,
    ) -> Result<UpdateContactResponse> {
        let path = format!("/contacts/{contact_id_or_email}/topics");

        let request = self.0.build(Method::PATCH, &path);
        let response = self.0.send(request.json(&topics.into())).await?;
        let content = response.json::<UpdateContactResponse>().await?;

        Ok(content)
    }

    /// Add an existing contact to a segment.
    ///
    /// <https://resend.com/docs/api-reference/contacts/add-contact-to-segment>
    #[maybe_async::maybe_async]
    pub async fn add_contact_segment(
        &self,
        contact_id_or_email: &str,
        segment_id: &str,
    ) -> Result<AddContactSegmentResponse> {
        let path = format!("/contacts/{contact_id_or_email}/segments/{segment_id}");

        let request = self.0.build(Method::POST, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<AddContactSegmentResponse>().await?;

        Ok(content)
    }

    /// Remove an existing contact from a segment.
    ///
    /// <https://resend.com/docs/api-reference/contacts/delete-contact-segment>
    #[maybe_async::maybe_async]
    pub async fn delete_contact_segment(
        &self,
        contact_id_or_email: &str,
        segment_id: &str,
    ) -> Result<RemoveContactSegmentResponse> {
        let path = format!("/contacts/{contact_id_or_email}/segments/{segment_id}");

        let request = self.0.build(Method::DELETE, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<RemoveContactSegmentResponse>().await?;

        Ok(content)
    }

    /// Retrieve a list of segments that a contact is part of.
    ///
    /// <https://resend.com/docs/api-reference/contacts/list-contact-segments>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn list_contact_segment<T>(
        &self,
        contact_id_or_email: &str,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<Segment>> {
        let path = format!("/contacts/{contact_id_or_email}/segments/");

        let request = self.0.build(Method::GET, &path).query(&list_opts);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<Segment>>().await?;

        Ok(content)
    }

    /// Create a custom property for your contacts.
    ///
    /// <https://resend.com/docs/api-reference/contact-properties/create-contact-property>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn create_property(
        &self,
        contact_property: CreateContactPropertyOptions,
    ) -> Result<CreateContactPropertyResponse> {
        let path = "/contact-properties";

        let request = self.0.build(Method::POST, path);
        let response = self.0.send(request.json(&contact_property)).await?;
        let content = response.json::<CreateContactPropertyResponse>().await?;

        Ok(content)
    }

    /// Retrieve a contact property by its ID.
    ///
    /// <https://resend.com/docs/api-reference/contact-properties/get-contact-property>
    #[maybe_async::maybe_async]
    pub async fn get_property(&self, contact_property_id: &str) -> Result<ContactProperty> {
        let path = format!("/contact-properties/{contact_property_id}");

        let request = self.0.build(Method::GET, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<ContactProperty>().await?;

        Ok(content)
    }

    /// Update an existing contact property.
    ///
    /// <https://resend.com/docs/api-reference/contact-properties/update-contact-property>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn update_property(
        &self,
        contact_property_id: &str,
        update: ContactPropertyChanges,
    ) -> Result<UpdateContactPropertyResponse> {
        let path = format!("/contact-properties/{contact_property_id}");

        let request = self.0.build(Method::PATCH, &path);
        let response = self.0.send(request.json(&update)).await?;
        let content = response.json::<UpdateContactPropertyResponse>().await?;

        Ok(content)
    }

    /// Remove an existing contact property.
    ///
    /// <https://resend.com/docs/api-reference/contact-properties/delete-contact-property>
    #[maybe_async::maybe_async]
    pub async fn delete_property(
        &self,
        contact_property_id: &str,
    ) -> Result<DeleteContactPropertyResponse> {
        let path = format!("/contact-properties/{contact_property_id}");

        let request = self.0.build(Method::DELETE, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<DeleteContactPropertyResponse>().await?;

        Ok(content)
    }

    /// Retrieve a list of contact properties.
    ///
    /// - Default limit: 20
    ///
    /// <https://resend.com/docs/api-reference/contact-properties/list-contact-properties>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn list_properties<T>(
        &self,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<ContactProperty>> {
        let path = "/contact-properties";

        let request = self.0.build(Method::GET, path).query(&list_opts);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<ContactProperty>>().await?;

        Ok(content)
    }
}

impl fmt::Debug for ContactsSvc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

#[allow(unreachable_pub)]
pub mod types {
    use serde::{Deserialize, Serialize};

    use crate::{
        topics::types::TopicId,
        types::{SegmentId, SubscriptionType},
    };

    crate::define_id_type!(ContactId);
    crate::define_id_type!(ContactPropertyId);

    /// Details of a new [`Contact`].
    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct CreateContactOptions {
        /// Email address of the contact.
        email: String,

        /// The Audience ID.
        pub(crate) audience_id: Option<String>,

        /// First name of the contact.
        #[serde(skip_serializing_if = "Option::is_none")]
        first_name: Option<String>,
        /// Last name of the contact.
        #[serde(skip_serializing_if = "Option::is_none")]
        last_name: Option<String>,
        /// Indicates if the contact is unsubscribed.
        #[serde(skip_serializing_if = "Option::is_none")]
        unsubscribed: Option<bool>,
    }

    impl CreateContactOptions {
        /// Creates a new [`ContactData`].
        pub fn new(email: &str) -> Self {
            Self {
                email: email.to_owned(),
                audience_id: None,
                first_name: None,
                last_name: None,
                unsubscribed: None,
            }
        }

        /// Adds the audience id to the contact.
        #[inline]
        pub fn with_audience_id(mut self, audience_id: &str) -> Self {
            self.audience_id = Some(audience_id.to_owned());
            self
        }

        /// Adds the first name to the contact.
        #[inline]
        pub fn with_first_name(mut self, name: &str) -> Self {
            self.first_name = Some(name.to_owned());
            self
        }

        /// Adds the last name to the contact.
        #[inline]
        pub fn with_last_name(mut self, name: &str) -> Self {
            self.last_name = Some(name.to_owned());
            self
        }

        /// Toggles the unsubscribe status to `unsubscribe`.
        #[inline]
        pub const fn with_unsubscribed(mut self, unsubscribed: bool) -> Self {
            self.unsubscribed = Some(unsubscribed);
            self
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CreateContactResponse {
        /// Unique identifier for the created contact.
        pub id: ContactId,
    }

    /// Details of an existing contact.
    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Contact {
        /// Unique identifier for the contact.
        pub id: ContactId,
        /// Email address of the contact.
        pub email: String,
        /// First name of the contact.
        pub first_name: String,
        /// Last name of the contact.
        pub last_name: String,
        /// Indicates if the contact is unsubscribed.
        pub unsubscribed: bool,
        /// Timestamp indicating when the contact was created in ISO8601 format.
        pub created_at: String,
    }

    /// List of changes to apply to a [`Contact`].
    #[must_use]
    #[derive(Debug, Default, Clone, Serialize)]
    pub struct ContactChanges {
        /// First name of the contact.
        #[serde(skip_serializing_if = "Option::is_none")]
        first_name: Option<String>,
        /// Last name of the contact.
        #[serde(skip_serializing_if = "Option::is_none")]
        last_name: Option<String>,
        /// Indicates the subscription status of the contact.
        #[serde(skip_serializing_if = "Option::is_none")]
        unsubscribed: Option<bool>,
    }

    impl ContactChanges {
        /// Creates a new [`ContactChanges`].
        #[inline]
        pub fn new() -> Self {
            Self::default()
        }

        /// Updates the first name of the contact.
        #[inline]
        pub fn with_first_name(mut self, name: &str) -> Self {
            self.first_name = Some(name.to_owned());
            self
        }

        /// Updates the last name of the contact.
        #[inline]
        pub fn with_last_name(mut self, name: &str) -> Self {
            self.last_name = Some(name.to_owned());
            self
        }

        /// Updates the unsubscribe status of the contact.
        #[inline]
        pub const fn with_unsubscribed(mut self, unsubscribed: bool) -> Self {
            self.unsubscribed = Some(unsubscribed);
            self
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct UpdateContactResponse {
        /// Unique identifier for the updated contact.
        pub id: ContactId,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DeleteContactResponse {
        /// The ID of the contact.
        #[allow(dead_code)]
        pub contact: ContactId,
        /// Indicates whether the contact was deleted successfully.
        pub deleted: bool,
    }

    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct ContactTopic {
        pub id: TopicId,
        pub name: String,
        pub description: Option<String>,
        pub subscription: SubscriptionType,
        pub created_at: String,
    }

    /// See [relevant docs].
    ///
    /// [relevant docs]: <https://resend.com/docs/api-reference/contacts/update-contact-topic#body-parameters>
    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct UpdateContactTopicOptions {
        id: String,
        subscription: SubscriptionType,
    }

    impl UpdateContactTopicOptions {
        /// `id`: The Topic ID.
        /// `subscription`: The subscription action.
        pub fn new(id: impl Into<String>, subscription: SubscriptionType) -> Self {
            Self {
                id: id.into(),
                subscription,
            }
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AddContactSegmentResponse {
        pub id: SegmentId,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct RemoveContactSegmentResponse {
        pub id: SegmentId,
        pub deleted: bool,
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy)]
    #[must_use]
    #[serde(rename_all = "snake_case")]
    pub enum PropertyType {
        String,
        Number,
    }

    /// Details of a new [`ContactProperty`].
    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct CreateContactPropertyOptions {
        key: String,
        #[serde(rename = "type")]
        r#type: PropertyType,
        fallback_value: Option<serde_json::Value>,
    }

    impl CreateContactPropertyOptions {
        /// - `key`: The property key. Max length is `50` characters. Only alphanumeric characters
        ///   and underscores are allowed.
        /// - `r#type`: The property type.
        pub fn new(key: impl Into<String>, r#type: PropertyType) -> Self {
            Self {
                key: key.into(),
                r#type,
                fallback_value: None,
            }
        }

        /// The default value to use when the property is not set for a contact. Must match the
        /// type specified in the `r#type` field.
        pub fn with_fallback(mut self, fallback: impl Into<serde_json::Value>) -> Self {
            self.fallback_value = Some(fallback.into());
            self
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CreateContactPropertyResponse {
        pub id: ContactPropertyId,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ContactProperty {
        pub id: ContactPropertyId,
        pub created_at: String,
        pub key: String,
        #[serde(rename = "type")]
        pub r#type: PropertyType,
        pub fallback_value: Option<serde_json::Value>,
    }

    /// List of changes to apply to a [`ContactProperty`].
    #[must_use]
    #[derive(Debug, Default, Clone, Serialize)]
    pub struct ContactPropertyChanges {
        #[serde(skip_serializing_if = "Option::is_none")]
        fallback_value: Option<serde_json::Value>,
    }

    impl ContactPropertyChanges {
        /// The default value to use when the property is not set for a contact. Must match the
        /// type of the property.
        pub fn with_fallback(mut self, fallback: impl Into<serde_json::Value>) -> Self {
            self.fallback_value = Some(fallback.into());
            self
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct UpdateContactPropertyResponse {
        /// Unique identifier for the updated contact property.
        pub id: ContactPropertyId,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DeleteContactPropertyResponse {
        #[allow(dead_code)]
        pub id: ContactPropertyId,
        pub deleted: bool,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::needless_return)]
mod test {
    use crate::list_opts::ListOptions;
    use crate::test::{CLIENT, DebugResult};
    use crate::types::{
        ContactChanges, ContactProperty, CreateContactOptions, CreateTopicOptions,
        SubscriptionType, UpdateContactTopicOptions,
    };

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    async fn no_audience() -> DebugResult<()> {
        let resend = &*CLIENT;

        let contact = CreateContactOptions::new("steve.wozniak@gmail.com")
            .with_first_name("Steve")
            .with_last_name("Wozniak")
            .with_unsubscribed(false);
        let id = resend.contacts.create(contact).await?;
        std::thread::sleep(std::time::Duration::from_secs(4));

        let deleted = resend.contacts.delete(&id).await?;
        assert!(deleted);

        std::thread::sleep(std::time::Duration::from_secs(4));

        Ok(())
    }

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    #[ignore = "Flaky backend"]
    async fn all() -> DebugResult<()> {
        let resend = &*CLIENT;
        let audience = "test_contacts";

        // Create audience.
        let audience = resend.segments.create(audience).await?;
        let audience_id = audience.id;
        std::thread::sleep(std::time::Duration::from_secs(4));

        // Create.
        let contact = CreateContactOptions::new("antonios.barotsis@pm.me")
            .with_first_name("Antonios")
            .with_last_name("Barotsis")
            .with_unsubscribed(false)
            .with_audience_id(&audience_id);
        let id = resend.contacts.create(contact).await?;
        std::thread::sleep(std::time::Duration::from_secs(4));

        // Get topic
        let topics = resend
            .contacts
            .get_contact_topics(&id, ListOptions::default())
            .await?;
        assert!(topics.data.is_empty());

        // Update topic
        let topic = resend
            .topics
            .create(CreateTopicOptions::new(
                "Weekly Newsletter",
                SubscriptionType::OptIn,
            ))
            .await?;
        let topics = [UpdateContactTopicOptions::new(
            topic.id.to_string(),
            SubscriptionType::OptIn,
        )];
        let _topics = resend.contacts.update_contact_topics(&id, topics).await?;
        std::thread::sleep(std::time::Duration::from_secs(4));

        // Get topic
        let topics = resend
            .contacts
            .get_contact_topics(&id, ListOptions::default())
            .await?;
        assert!(!topics.data.is_empty());

        // Update.
        let changes = ContactChanges::new().with_unsubscribed(true);
        let _contact = resend.contacts.update(&id, changes).await?;
        std::thread::sleep(std::time::Duration::from_secs(4));

        // Retrieve.
        let contact = resend.contacts.get(&id).await?;
        assert!(contact.unsubscribed);

        // Retrieve by email.
        let contact = resend.contacts.get("antonios.barotsis@pm.me").await?;
        assert!(contact.unsubscribed);

        // List.
        let contacts = resend
            .contacts
            .list(&audience_id, ListOptions::default())
            .await?;
        assert_eq!(contacts.len(), 1);

        // Delete.
        let deleted = resend.contacts.delete(&id).await?;
        assert!(deleted);

        // Delete audience.
        let deleted = resend.segments.delete(&audience_id.clone()).await?;
        assert!(deleted);
        std::thread::sleep(std::time::Duration::from_secs(1));

        // Delete topic
        let deleted = resend.topics.delete(&topic.id).await?;
        assert!(deleted.deleted);

        // List.
        let contacts = resend
            .contacts
            .list(&audience_id, ListOptions::default())
            .await?;
        assert!(contacts.is_empty());

        std::thread::sleep(std::time::Duration::from_secs(4));

        Ok(())
    }

    #[ignore = "Flaky backend"]
    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    async fn segments() -> DebugResult<()> {
        let resend = &*CLIENT;

        // Create segment
        let segment = resend.segments.create("registered users").await?;
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Create contact
        let contact = CreateContactOptions::new("antonios.barotsis@pm.me")
            .with_first_name("Antonios")
            .with_last_name("Barotsis");
        let contact_id = resend.contacts.create(contact).await?;
        std::thread::sleep(std::time::Duration::from_secs(2));

        let _added = resend
            .contacts
            .add_contact_segment(&contact_id, &segment.id)
            .await?;
        std::thread::sleep(std::time::Duration::from_secs(4));

        let list = resend
            .contacts
            .list_contact_segment(&contact_id, ListOptions::default())
            .await?;
        assert!(!list.data.is_empty());

        let deleted = resend
            .contacts
            .delete_contact_segment(&contact_id, &segment.id)
            .await?;
        assert!(deleted.deleted);
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Delete
        let deleted = resend.contacts.delete(&contact_id).await?;
        assert!(deleted);
        let deleted = resend.segments.delete(&segment.id).await?;
        assert!(deleted);

        std::thread::sleep(std::time::Duration::from_secs(4));

        Ok(())
    }

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    async fn properties() -> DebugResult<()> {
        use crate::{
            contacts::types::ContactPropertyChanges,
            types::{CreateContactPropertyOptions, PropertyType},
        };

        let resend = &*CLIENT;

        // Create
        let contact_property =
            CreateContactPropertyOptions::new("company_name", PropertyType::String)
                .with_fallback("Acme Corp");
        let contact_property = resend.contacts.create_property(contact_property).await?;
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Get
        let contact_property = resend.contacts.get_property(&contact_property.id).await?;

        // Update
        let update = ContactPropertyChanges::default().with_fallback("Example Company");
        let contact_property = resend
            .contacts
            .update_property(&contact_property.id, update)
            .await?;

        // List
        let contact_properties = resend
            .contacts
            .list_properties(ListOptions::default())
            .await?;
        assert!(!contact_properties.is_empty());

        // Delete
        let deleted = resend
            .contacts
            .delete_property(&contact_property.id)
            .await?;
        assert!(deleted.deleted);

        std::thread::sleep(std::time::Duration::from_secs(4));

        Ok(())
    }

    #[test]
    fn deserialize_test() {
        let contact_property = r#"{
  "object": "contact_property",
  "id": "b6d24b8e-af0b-4c3c-be0c-359bbd97381e",
  "key": "company_name",
  "type": "string",
  "fallback_value": "Acme Corp",
  "created_at": "2023-04-08T00:11:13.110779+00:00"
}"#;

        let res = serde_json::from_str::<ContactProperty>(contact_property);
        assert!(res.is_ok());
    }
}