mailtrap 0.3.1

An unofficial library for interacting with the Mailtrap API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use anyhow::{Error, Result, anyhow};
use reqwest::{Client, Method, Url};
use serde::{Deserialize, Serialize, de::Deserializer, ser::Serializer};
use std::fmt::{self, Display};

/// Default base URL for the Mailtrap API.
const DEFAULT_URL: &str = "https://mailtrap.io";

/// Path for account access API endpoints.
const ACCESS_URL_PATH: &str = "/api/accounts";

/// Helper function to construct the access URL with the default base URL.
///
/// # Arguments
///
/// * `account_id` - The ID of the account.
/// * `domain_ids` - Optional list of domain IDs to filter by.
/// * `inbox_ids` - Optional list of inbox IDs to filter by.
/// * `project_ids` - Optional list of project IDs to filter by.
///
/// # Returns
///
/// Returns a `Result` containing a `Url` on success, or an `Error` on failure.
fn default_access_url_with_params(
    account_id: &str,
    domain_ids: Option<Vec<&str>>,
    inbox_ids: Option<Vec<&str>>,
    project_ids: Option<Vec<&str>>,
) -> Result<Url, Error> {
    if account_id.is_empty() {
        return Err(anyhow!("Account ID is empty"));
    }
    let url = DEFAULT_URL.trim_end_matches('/');
    let url = format!("{}{}/{}/account_access", url, ACCESS_URL_PATH, account_id);
    let mut url = Url::parse(&url)?;
    let mut params = Vec::<String>::new();
    if let Some(domain_ids) = domain_ids {
        params.push(format!("domain_ids=[{}]", domain_ids.join(",")));
    }
    if let Some(inbox_ids) = inbox_ids {
        params.push(format!("inbox_ids=[{}]", inbox_ids.join(",")));
    }
    if let Some(project_ids) = project_ids {
        params.push(format!("project_ids=[{}]", project_ids.join(",")));
    }
    if !params.is_empty() {
        url.set_query(Some(&params.join("&")));
    }
    Ok(url)
}

/// Helper function to construct the access URL with a custom base URL.
///
/// # Arguments
///
/// * `url` - The base URL of the API. A value of `None` will use the default base URL.
/// * `account_id` - The ID of the account.
/// * `domain_ids` - Optional list of domain IDs to filter by.
/// * `inbox_ids` - Optional list of inbox IDs to filter by.
/// * `project_ids` - Optional list of project IDs to filter by.
///
/// # Returns
///
/// Returns a `Result` containing a `Url` on success, or an `Error` on failure.
fn access_url_with_params(
    url: &str,
    account_id: &str,
    domain_ids: Option<Vec<&str>>,
    inbox_ids: Option<Vec<&str>>,
    project_ids: Option<Vec<&str>>,
) -> Result<Url, Error> {
    if url.is_empty() {
        return Err(anyhow!("URL is empty"));
    }
    if account_id.is_empty() {
        return Err(anyhow!("Account ID is empty"));
    }
    let url = url.trim_end_matches('/');
    let url = format!("{}{}/{}/account_access", url, ACCESS_URL_PATH, account_id);
    let mut url = Url::parse(&url)?;
    let mut params = Vec::<String>::new();
    if let Some(domain_ids) = domain_ids {
        params.push(format!("domain_ids=[{}]", domain_ids.join(",")));
    }
    if let Some(inbox_ids) = inbox_ids {
        params.push(format!("inbox_ids=[{}]", inbox_ids.join(",")));
    }
    if let Some(project_ids) = project_ids {
        params.push(format!("project_ids=[{}]", project_ids.join(",")));
    }
    if !params.is_empty() {
        url.set_query(Some(&params.join("&")));
    }
    Ok(url)
}

/// Helper function to construct the remove access URL with the default base URL.
///
/// # Arguments
///
/// * `account_id` - The ID of the account.
/// * `account_access_id` - The ID of the account access.
///
/// # Returns
///
/// Returns a `Result` containing a `Url` on success, or an `Error` on failure.
fn default_remove_access_url_with_params(
    account_id: &str,
    account_access_id: &str,
) -> Result<Url, Error> {
    if account_id.is_empty() {
        return Err(anyhow!("Account ID is empty"));
    }
    if account_access_id.is_empty() {
        return Err(anyhow!("Account access ID is empty"));
    }
    let url = DEFAULT_URL.trim_end_matches('/');
    let url = format!(
        "{}{}/{}/account_accesses/{}",
        url, ACCESS_URL_PATH, account_id, account_access_id
    );
    Ok(Url::parse(&url)?)
}

/// Helper function to construct the remove access URL with a custom base URL.
///
/// # Arguments
///
/// * `url` - The base URL of the API. A value of `None` will use the default base URL.
/// * `account_id` - The ID of the account.
/// * `account_access_id` - The ID of the account access.
///
/// # Returns
///
/// Returns a `Result` containing a `Url` on success, or an `Error` on failure.
fn remove_access_url_with_params(
    url: &str,
    account_id: &str,
    account_access_id: &str,
) -> Result<Url, Error> {
    if url.is_empty() {
        return Err(anyhow!("URL is empty"));
    }
    if account_id.is_empty() {
        return Err(anyhow!("Account ID is empty"));
    }
    if account_access_id.is_empty() {
        return Err(anyhow!("Account access ID is empty"));
    }
    let url = url.trim_end_matches('/');
    let url = format!(
        "{}{}/{}/account_accesses/{}",
        url, ACCESS_URL_PATH, account_id, account_access_id
    );
    Ok(Url::parse(&url)?)
}

/// Represents the type of entity that has access.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum AccessSpecifierType {
    /// A regular user.
    User,
    /// An invited user.
    Invite,
    /// An API token.
    ApiToken,
}

impl AccessSpecifierType {
    /// Creates a new `AccessSpecifierType` from a string slice.
    ///
    /// # Arguments
    ///
    /// * `specifier_type` - The string representation of the specifier type ("user", "invite", or "api_token").
    pub fn new(specifier_type: &str) -> Result<Self, Error> {
        match specifier_type {
            "user" => Ok(Self::User),
            "invite" => Ok(Self::Invite),
            "api_token" => Ok(Self::ApiToken),
            _ => Err(anyhow!("Invalid specifier type: {}", specifier_type)),
        }
    }

    /// Returns the string representation of the specifier type.
    pub fn to_string(&self) -> String {
        match self {
            Self::User => "user".to_string(),
            Self::Invite => "invite".to_string(),
            Self::ApiToken => "api_token".to_string(),
        }
    }

    /// Creates a new `AccessSpecifierType` from a `String`.
    pub fn from_string(specifier_type: String) -> Result<Self, Error> {
        Self::new(&specifier_type.as_str())
    }

    /// Creates a new `AccessSpecifierType` from a string slice.
    pub fn from_str(specifier_type: &str) -> Result<Self, Error> {
        Self::new(specifier_type)
    }
}

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

/// Details about the entity holding the access.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessSpecifier {
    /// Unique identifier for the specifier.
    pub id: i64,
    /// Email address associated with the specifier.
    pub email: String,
    /// Name of the specifier.
    pub name: String,
    /// Whether two-factor authentication is enabled for this specifier.
    pub two_factor_authentication_enabled: bool,
}

/// Represents the type of resource being accessed.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AccessResourceType {
    /// An account resource.
    Account,
    /// A billing resource.
    Billing,
    /// A project resource.
    Project,
    /// An inbox resource.
    Inbox,
    /// A sending domain resource.
    SendingDomain,
    /// An email campaign permission scope resource.
    EmailCampaignPermissionScope,
}

impl AccessResourceType {
    /// Creates a new `AccessResourceType` from a string slice.
    ///
    /// # Arguments
    ///
    /// * `resource_type` - The string representation of the resource type.
    pub fn new(resource_type: &str) -> Result<Self, Error> {
        match resource_type {
            "account" => Ok(Self::Account),
            "billing" => Ok(Self::Billing),
            "project" => Ok(Self::Project),
            "inbox" => Ok(Self::Inbox),
            "sending_domain" => Ok(Self::SendingDomain),
            "email_campaign_permission_scope" => Ok(Self::EmailCampaignPermissionScope),
            _ => Err(anyhow!("Invalid resource type: {}", resource_type)),
        }
    }

    /// Returns the string representation of the resource type.
    pub fn to_string(&self) -> String {
        match self {
            Self::Account => "account".to_string(),
            Self::Billing => "billing".to_string(),
            Self::Project => "project".to_string(),
            Self::Inbox => "inbox".to_string(),
            Self::SendingDomain => "sending_domain".to_string(),
            Self::EmailCampaignPermissionScope => "email_campaign_permission_scope".to_string(),
        }
    }

    /// Creates a new `AccessResourceType` from a `String`.
    pub fn from_string(resource_type: String) -> Result<Self, Error> {
        Self::new(&resource_type.as_str())
    }

    /// Creates a new `AccessResourceType` from a string slice.
    pub fn from_str(resource_type: &str) -> Result<Self, Error> {
        Self::new(resource_type)
    }
}

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

/// Represents the level of access granted to a resource.
#[derive(Debug, PartialEq)]
pub enum AccessResourceAccessLevel {
    /// Full ownership access (level 1000).
    Owner,
    /// Administrative access (level 100).
    Admin,
    /// Enhanced viewer access (level 50).
    ViewerPlus,
    /// Viewer access (level 10).
    Viewer,
    /// Indeterminate access level (level 1).
    Indeterminate,
}

impl AccessResourceAccessLevel {
    /// Creates a new `AccessResourceAccessLevel` from an integer value.
    ///
    /// # Arguments
    ///
    /// * `access_level` - The integer representation of the access level.
    pub fn new(access_level: i64) -> Result<Self, Error> {
        match access_level {
            1000 => Ok(Self::Owner),
            100 => Ok(Self::Admin),
            50 => Ok(Self::ViewerPlus),
            10 => Ok(Self::Viewer),
            1 => Ok(Self::Indeterminate),
            _ => Err(anyhow!("Invalid access level: {}", access_level)),
        }
    }

    /// Returns the integer representation of the access level.
    pub fn to_int(&self) -> i64 {
        match self {
            Self::Owner => 1000,
            Self::Admin => 100,
            Self::ViewerPlus => 50,
            Self::Viewer => 10,
            Self::Indeterminate => 1,
        }
    }

    /// Creates a new `AccessResourceAccessLevel` from an integer.
    pub fn from_int(access_level: i64) -> Result<Self, Error> {
        Self::new(access_level)
    }

    /// Returns the string representation of the access level.
    pub fn to_string(&self) -> String {
        match self {
            Self::Owner => "owner".to_string(),
            Self::Admin => "admin".to_string(),
            Self::ViewerPlus => "viewer_plus".to_string(),
            Self::Viewer => "viewer".to_string(),
            Self::Indeterminate => "indeterminate".to_string(),
        }
    }

    /// Creates a new `AccessResourceAccessLevel` from a string representation of the integer value.
    pub fn from_string(access_level: String) -> Result<Self, Error> {
        let access_level = access_level.parse::<i64>()?;
        Self::new(access_level)
    }

    /// Creates a new `AccessResourceAccessLevel` from a string slice representation of the integer value.
    pub fn from_str(access_level: &str) -> Result<Self, Error> {
        let access_level = access_level.parse::<i64>()?;
        Self::new(access_level)
    }
}

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

impl Serialize for AccessResourceAccessLevel {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i64(self.to_int())
    }
}

impl<'de> Deserialize<'de> for AccessResourceAccessLevel {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let access_level = i64::deserialize(deserializer)?;
        Self::new(access_level).map_err(serde::de::Error::custom)
    }
}
/// Represents a specific resource and the access level granted to it.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessResource {
    /// The ID of the resource.
    pub resource_id: i64,
    /// The type of the resource.
    pub resource_type: AccessResourceType,
    /// The level of access granted to this resource.
    pub access_level: AccessResourceAccessLevel,
}

/// Defines specific permissions granted.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessPermission {
    /// Whether read access is granted.
    pub can_read: bool,
    /// Whether update access is granted.
    pub can_update: bool,
    /// Whether delete/destroy access is granted.
    pub can_destroy: bool,
    /// Whether the user can leave the resource.
    pub can_leave: bool,
}

/// Represents a complete access record returned by the API.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessRecord {
    /// Unique identifier for the access record.
    pub id: i64,
    /// The type of the specifier (user, invite, etc.).
    pub specifier_type: AccessSpecifierType,
    /// Detailed information about the specifier.
    pub specifier: AccessSpecifier,
    /// List of resources associated with this access record.
    pub resources: Vec<AccessResource>,
    /// Specific permissions granted.
    pub permissions: AccessPermission,
}

/// Represents an error response from the API with a single error message.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessErrorResponse {
    /// The error message.
    pub error: String,
}

/// Represents an error response from the API with multiple error messages.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessErrorsResponse {
    /// List of error messages.
    pub errors: Vec<String>,
}

/// Represents the response from removing an access record.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccessRemoveResponse {
    /// The ID of the removed access record.
    pub id: i64,
}

/// Client for interacting with the Mailtrap Access API.
#[derive(Debug, PartialEq, Clone)]
pub struct Access {}

impl Access {
    /// Creates a new `Access` client instance.
    pub fn new() -> Self {
        Self {}
    }

    /// Lists access records for a given account.
    ///
    /// # Arguments
    ///
    /// * `api_url` - Optional custom API URL. A value of `None` will use the default base URL.
    /// * `api_key` - Optional API key for authentication.
    /// * `bearer_token` - Optional Bearer token for authentication.
    /// * `account_id` - The ID of the account to list access for.
    /// * `domain_ids` - Optional list of domain IDs to filter by.
    /// * `inbox_ids` - Optional list of inbox IDs to filter by.
    /// * `project_ids` - Optional list of project IDs to filter by.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of `AccessRecord`s on success, or an `Error` on failure.
    pub async fn list(
        &self,
        api_url: Option<&str>,
        api_key: Option<&str>,
        bearer_token: Option<&str>,
        account_id: &str,
        domain_ids: Option<Vec<&str>>,
        inbox_ids: Option<Vec<&str>>,
        project_ids: Option<Vec<&str>>,
    ) -> Result<Vec<AccessRecord>, Error> {
        if api_key.is_none() && bearer_token.is_none() {
            return Err(anyhow!("API key or bearer token is required"));
        }
        if api_key.is_some_and(|key| key.is_empty()) {
            return Err(anyhow!("API key is empty"));
        }
        if bearer_token.is_some_and(|token| token.is_empty()) {
            return Err(anyhow!("Bearer token is empty"));
        }

        if account_id.is_empty() {
            return Err(anyhow!("Account ID is empty"));
        }

        if domain_ids.clone().is_some() {
            if domain_ids.clone().unwrap().is_empty() {
                return Err(anyhow!("Domain IDs are empty"));
            }
            for id in domain_ids.clone().unwrap() {
                if id.is_empty() {
                    return Err(anyhow!("Domain IDs are empty"));
                }
            }
        }
        if inbox_ids.clone().is_some() {
            if inbox_ids.clone().unwrap().is_empty() {
                return Err(anyhow!("Inbox IDs are empty"));
            }
            for id in inbox_ids.clone().unwrap() {
                if id.is_empty() {
                    return Err(anyhow!("Inbox IDs are empty"));
                }
            }
        }
        if project_ids.clone().is_some() {
            if project_ids.clone().unwrap().is_empty() {
                return Err(anyhow!("Project IDs are empty"));
            }
            for id in project_ids.clone().unwrap() {
                if id.is_empty() {
                    return Err(anyhow!("Project IDs are empty"));
                }
            }
        }

        let url = match api_url {
            Some(url) => {
                if url.is_empty() {
                    return Err(anyhow!("URL is empty"));
                }
                let url = Url::parse(url).map_err(|e| anyhow!("Failed to parse URL: {}", e))?;
                access_url_with_params(
                    url.as_str(),
                    account_id,
                    domain_ids,
                    inbox_ids,
                    project_ids,
                )?
            }
            None => default_access_url_with_params(account_id, domain_ids, inbox_ids, project_ids)?,
        };

        let client = Client::new();
        let mut request = client.request(Method::GET, url.clone());

        if api_key.is_some() {
            request = request.header("Api-Token", api_key.unwrap());
        }

        if bearer_token.is_some() {
            request = request.header("Authorization", format!("Bearer {}", bearer_token.unwrap()));
        }

        let response = match request.send().await {
            Ok(response) => response,
            Err(e) => return Err(anyhow!("Failed to get access list: {}", e)),
        };

        let status = response.status();

        if !status.is_success() {
            match status.as_u16() {
                401 => {
                    let body = match response.json::<AccessErrorResponse>().await {
                        Ok(body) => body,
                        Err(e) => return Err(anyhow!("Failed to parse response: {}", e)),
                    };
                    return Err(anyhow!("Failed to get access list: {}", body.error));
                }
                403 => {
                    let body = match response.json::<AccessErrorsResponse>().await {
                        Ok(body) => body,
                        Err(e) => return Err(anyhow!("Failed to parse response: {}", e)),
                    };
                    return Err(anyhow!(
                        "Failed to get access list: {}",
                        body.errors.join(": ")
                    ));
                }
                _ => return Err(anyhow!("Failed to get access list: {}", status)),
            }
        }

        match response.json::<Vec<AccessRecord>>().await {
            Ok(body) => Ok(body),
            Err(e) => Err(anyhow!("Failed to parse response: {}", e)),
        }
    }

    /// Removes an access record for a given account.
    ///
    /// # Arguments
    ///
    /// * `api_url` - Optional custom API URL. A value of `None` will use the default base URL.
    /// * `api_key` - Optional API key for authentication.
    /// * `bearer_token` - Optional Bearer token for authentication.
    /// * `account_id` - The ID of the account to remove access for.
    /// * `account_access_id` - The ID of the account access to remove.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a `AccessRemoveResponse` on success, or an `Error` on failure.
    pub async fn remove(
        &self,
        api_url: Option<&str>,
        api_key: Option<&str>,
        bearer_token: Option<&str>,
        account_id: &str,
        account_access_id: &str,
    ) -> Result<AccessRemoveResponse, Error> {
        if api_key.is_none() && bearer_token.is_none() {
            return Err(anyhow!("API key or bearer token is required"));
        }
        if api_key.is_some_and(|key| key.is_empty()) {
            return Err(anyhow!("API key is empty"));
        }
        if bearer_token.is_some_and(|token| token.is_empty()) {
            return Err(anyhow!("Bearer token is empty"));
        }
        if account_id.is_empty() {
            return Err(anyhow!("Account ID is empty"));
        }
        if account_access_id.is_empty() {
            return Err(anyhow!("Account access ID is empty"));
        }

        let url = match api_url {
            Some(url) => {
                if url.is_empty() {
                    return Err(anyhow!("URL is empty"));
                }
                let url = Url::parse(url).map_err(|e| anyhow!("Failed to parse URL: {}", e))?;
                remove_access_url_with_params(url.as_str(), account_id, account_access_id)?
            }
            None => default_remove_access_url_with_params(account_id, account_access_id)?,
        };

        let client = Client::new();
        let mut request = client.request(Method::DELETE, url.clone());

        if api_key.is_some() {
            request = request.header("Api-Token", api_key.unwrap());
        }

        if bearer_token.is_some() {
            request = request.header("Authorization", format!("Bearer {}", bearer_token.unwrap()));
        }

        let response = match request.send().await {
            Ok(response) => response,
            Err(e) => return Err(anyhow!("Failed to remove access: {}", e)),
        };

        let status = response.status();

        if !status.is_success() {
            match status.as_u16() {
                401 => {
                    let body = match response.json::<AccessErrorResponse>().await {
                        Ok(body) => body,
                        Err(e) => return Err(anyhow!("Failed to parse response: {}", e)),
                    };
                    return Err(anyhow!("Failed to remove access: {}", body.error));
                }
                403 => {
                    let body = match response.json::<AccessErrorsResponse>().await {
                        Ok(body) => body,
                        Err(e) => return Err(anyhow!("Failed to parse response: {}", e)),
                    };
                    return Err(anyhow!(
                        "Failed to remove access: {}",
                        body.errors.join(": ")
                    ));
                }
                404 => {
                    let body = match response.json::<AccessErrorResponse>().await {
                        Ok(body) => body,
                        Err(e) => return Err(anyhow!("Failed to parse response: {}", e)),
                    };
                    return Err(anyhow!("Failed to remove access: {}", body.error));
                }
                _ => return Err(anyhow!("Failed to remove access: {}", status)),
            }
        }
        match response.json::<AccessRemoveResponse>().await {
            Ok(body) => Ok(body),
            Err(e) => Err(anyhow!("Failed to parse response: {}", e)),
        }
    }
}

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

    #[test]
    fn test_default_access_url_fails_with_empty_account_id() {
        let url = default_access_url_with_params("", None, None, None);
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "Account ID is empty");
    }

    #[test]
    fn test_default_access_url_with_params() {
        let url = default_access_url_with_params(
            "1234567890",
            Some(vec!["1234567890"]),
            Some(vec!["1234567890"]),
            Some(vec!["1234567890"]),
        );
        assert_eq!(url.is_ok(), true);
        assert_eq!(
            url.unwrap().to_string(),
            "https://mailtrap.io/api/accounts/1234567890/account_access?domain_ids=[1234567890]&inbox_ids=[1234567890]&project_ids=[1234567890]"
        );
    }

    #[test]
    fn test_access_url_fails_with_empty_url() {
        let url = access_url_with_params("", "1234567890", None, None, None);
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "URL is empty");
    }

    #[test]
    fn test_access_url_with_params() {
        let url = access_url_with_params(
            "https://mailtrap.io/",
            "1234567890",
            Some(vec!["1234567890"]),
            Some(vec!["1234567890"]),
            Some(vec!["1234567890"]),
        );
        assert_eq!(url.is_ok(), true);
        assert_eq!(
            url.unwrap().to_string(),
            "https://mailtrap.io/api/accounts/1234567890/account_access?domain_ids=[1234567890]&inbox_ids=[1234567890]&project_ids=[1234567890]"
        );
    }

    #[test]
    fn test_default_remove_access_url_fails_with_empty_account_id() {
        let url = default_remove_access_url_with_params("", "1234567890");
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "Account ID is empty");
    }

    #[test]
    fn test_default_remove_access_url_fails_with_empty_account_access_id() {
        let url = default_remove_access_url_with_params("1234567890", "");
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "Account access ID is empty");
    }

    #[test]
    fn test_default_remove_access_url_with_params() {
        let url = default_remove_access_url_with_params("1234567890", "1234567890");
        assert_eq!(url.is_ok(), true);
        assert_eq!(
            url.unwrap().to_string(),
            "https://mailtrap.io/api/accounts/1234567890/account_accesses/1234567890"
        );
    }

    #[test]
    fn test_remove_access_url_fails_with_empty_url() {
        let url = remove_access_url_with_params("", "1234567890", "1234567890");
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "URL is empty");
    }

    #[test]
    fn test_remove_access_url_fails_with_empty_account_id() {
        let url = remove_access_url_with_params("https://mailtrap.io/", "", "1234567890");
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "Account ID is empty");
    }

    #[test]
    fn test_remove_access_url_fails_with_empty_account_access_id() {
        let url = remove_access_url_with_params("https://mailtrap.io/", "1234567890", "");
        assert_eq!(url.is_err(), true);
        assert_eq!(url.unwrap_err().to_string(), "Account access ID is empty");
    }

    #[test]
    fn test_remove_access_url_succeeds() {
        let url = remove_access_url_with_params("https://mailtrap.io/", "1234567890", "1234567890");
        assert_eq!(url.is_ok(), true);
        assert_eq!(
            url.unwrap().to_string(),
            "https://mailtrap.io/api/accounts/1234567890/account_accesses/1234567890"
        );
    }
}