routex-client-common 0.0.3

Common logic shared by different routex clients.
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
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]

use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, RwLock};

use anyhow::anyhow;
use base64::prelude::*;
use bytes::Bytes;
use futures::lock::Mutex;
use http::header::{
    ACCEPT, CONTENT_LENGTH, CONTENT_TYPE, HeaderMap, HeaderValue, InvalidHeaderValue, USER_AGENT,
};
use http::{Method, Request, StatusCode};
use routex_api::info::ConnectionInfo;
#[cfg(feature = "uniffi")]
use routex_api::info::CountryCode;
use routex_api::{Authenticated, ConnectionId, Error as ServiceError, Service, ServiceId};
#[cfg(feature = "error")]
use routex_api::{
    PaymentErrorCode, ProviderErrorCode, ServiceBlockedCode, TicketErrorCode,
    UnsupportedProductReason,
};
use routex_settlement::KeySettlement;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;

#[cfg(feature = "reqwest")]
pub use reqwest;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    RequestError(anyhow::Error),
    #[error("Service error")]
    ServiceError(ServiceError),
    #[error("Error response")]
    ResponseError(Box<Response>),
    #[error("Resource not found")]
    NotFound,
}

#[derive(Clone, Debug)]
pub struct Response {
    pub url: Url,
    pub status: StatusCode,
    pub headers: HeaderMap,
    pub body: Bytes,
}

pub fn json_decode<T: for<'de> Deserialize<'de>>(body: &[u8]) -> Result<T> {
    serde_json::from_slice(body).map_err(|err| Error::RequestError(err.into()))
}

impl From<Response> for Error {
    fn from(response: Response) -> Error {
        match serde_json::from_slice::<ServiceError>(&response.body) {
            Ok(payload) => Error::ServiceError(payload),
            Err(_) => Error::ResponseError(Box::new(response)),
        }
    }
}

pub trait HttpClient {
    fn execute(&self, req: Request<Vec<u8>>) -> impl Future<Output = Result<Response>>;
}

#[cfg(feature = "reqwest")]
impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Self::RequestError(anyhow!(err))
    }
}

#[cfg(feature = "reqwest")]
impl HttpClient for reqwest::Client {
    async fn execute(&self, req: Request<Vec<u8>>) -> Result<Response> {
        match self.execute(req.try_into()?).await {
            Ok(r) => Ok(Response {
                url: r.url().clone(),
                status: r.status(),
                headers: r.headers().clone(),
                body: r.bytes().await?,
            }),
            Err(err) => Err(err.into()),
        }
    }
}

pub type Result<T> = std::result::Result<T, Error>;

#[must_use]
#[derive(Clone, Debug)]
pub struct RoutexClientCore<C> {
    url: Url,
    user_agent: HeaderValue,
    http_client: C,
    keys: Arc<Mutex<HashMap<String, KeySettlement<sealed::RoutexKeySettlementEndpoint<C>>>>>,
    redirect_uri: Option<HeaderValue>,
    trace_id: Arc<RwLock<Option<Vec<u8>>>>,
}

mod sealed {
    use http::HeaderValue;
    use routex_settlement::KeySettlementCore;
    use url::Url;
    use uuid::Uuid;

    use super::{Error, HttpClient, RequestBuilder};

    #[derive(Debug)]
    pub struct RoutexKeySettlementEndpoint<C> {
        pub(super) url: Url,
        pub(super) user_agent: HeaderValue,
        pub(super) http_client: C,
    }

    impl<C> KeySettlementCore for RoutexKeySettlementEndpoint<C>
    where
        C: HttpClient,
    {
        type Data = Uuid;

        async fn request(
            &self,
            public_key: [u8; 32],
            ticket_id: &Self::Data,
        ) -> anyhow::Result<routex_api::keys::Response> {
            let request =
                RequestBuilder::post(&self.url, &routex_api::keys::Request { public_key })
                    .build(ticket_id, self.user_agent.clone());

            let response = self.http_client.execute(request).await?;

            if response.status.is_client_error() || response.status.is_server_error() {
                Err(Error::from(response).into())
            } else {
                Ok(serde_json::from_slice(&response.body)?)
            }
        }
    }
}

#[derive(Debug)]
pub struct RequestBuilder {
    request: Request<Vec<u8>>,
}

impl RequestBuilder {
    fn get(url: &Url) -> Self {
        let mut request = Request::new(Vec::new());

        *request.method_mut() = Method::GET;
        *request.uri_mut() = url.as_str().try_into().expect("URL to URI should work");

        Self { request }
    }

    fn post(url: &Url, json: &impl Serialize) -> Self {
        let mut request =
            Request::new(serde_json::to_vec(&json).expect("Serialization should work"));

        *request.method_mut() = Method::POST;
        *request.uri_mut() = url.as_str().try_into().expect("URL to URI should work");

        request
            .headers_mut()
            .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        Self { request }
    }

    fn build(mut self, ticket_id: &Uuid, user_agent: HeaderValue) -> Request<Vec<u8>> {
        self.request.headers_mut().extend([
            (
                routex_api::headers::TICKET_ID.clone(),
                HeaderValue::from_str(&ticket_id.to_string()).expect("ASCII"),
            ),
            (
                ACCEPT,
                HeaderValue::from_static(routex_api::CURRENT_MEDIA_TYPE),
            ),
            (USER_AGENT, user_agent),
        ]);

        self.request
    }
}

#[must_use]
pub struct SearchRequest<S, C>
where
    S: Service,
{
    inner: routex_api::info::Request,
    ticket: Authenticated<routex_api::Ticket<S>>,
    client: RoutexClientCore<C>,
}

impl<S, C> SearchRequest<S, C>
where
    S: Service,
    C: HttpClient + Clone,
{
    /// If IBAN detection is enabled and the first value of a [`SearchFilter::Term`] is detected
    /// to be a possible prefix of an IBAN that contains a national bank code,
    /// the result might contain additional connections that match that bank code.
    pub fn iban_detection(mut self, enable: bool) -> Self {
        self.inner.iban_detection = enable;
        self
    }

    /// Limit the number of results.
    pub fn limit(mut self, limit: impl Into<Option<usize>>) -> Self {
        self.inner.limit = limit.into();
        self
    }

    /// Details to contain in search results.
    pub fn details(mut self, details: impl IntoIterator<Item = routex_api::info::Details>) -> Self {
        self.inner.details = details.into_iter().collect();
        self
    }

    /// Send the request.
    ///
    /// # Errors
    ///
    /// Fails if the request fails.
    pub async fn send(self) -> Result<Vec<ConnectionInfo>> {
        json_decode(
            &self
                .client
                .execute(
                    &self.ticket,
                    self.client.post(
                        &routex_api::info::search_path().to_url(self.client.url()),
                        &self.inner,
                    ),
                )
                .await?,
        )
    }
}

pub const DEFAULT_URL: &str = "https://api.yaxi.tech/";

impl<C> RoutexClientCore<C>
where
    C: HttpClient + Clone,
{
    /// Create a new client for a versioned distribution and with a custom URL
    ///
    /// # Panics
    ///
    /// Panics if it fails to build the [`reqwest::Client`].
    pub fn for_distribution(distribution: &str, version: &str, url: Url, http_client: C) -> Self {
        Self {
            url,
            user_agent: format!(
                "RoutexClient/{} ({})",
                version,
                [distribution, std::env::consts::OS, std::env::consts::ARCH]
                    .into_iter()
                    .filter(|s| !s.is_empty())
                    .collect::<Vec<_>>()
                    .join("; "),
            )
            .try_into()
            .expect("Invalid header value"),
            http_client,
            keys: Arc::default(),
            redirect_uri: None,
            trace_id: Arc::default(),
        }
    }

    /// Run a key settlement with the routex service, verifying the attestation report.
    ///
    /// Stores a new random secret key and announces its public key to routex.
    /// In return, routex responds with its own public key and an attestation report.
    /// The attestation report allows verifying that routex created its corresponding secret key within the TEE
    /// and that its creation happened in response to our client public key (freshness).
    ///
    /// # Errors
    ///
    /// Returns an error if the key settlement request fails or the attestation report fails verification.
    pub async fn settle_key<S: routex_api::Service>(
        &self,
        ticket: &Authenticated<routex_api::Ticket<S>>,
    ) -> Result<()> {
        let ticket_id = ticket.to_data().id;

        self.with_key_settlement(ticket_id, async |keys| {
            keys.settle(&ticket_id).await.map_err(Error::RequestError)
        })
        .await
    }

    pub async fn with_key_settlement<U>(
        &self,
        ticket_id: Uuid,
        f: impl AsyncFnOnce(&mut KeySettlement<sealed::RoutexKeySettlementEndpoint<C>>) -> U,
    ) -> U {
        f(self
            .keys
            .lock()
            .await
            .entry(ticket_id.into())
            .or_insert_with(|| {
                KeySettlement::new(sealed::RoutexKeySettlementEndpoint {
                    url: routex_api::keys::settlement_path().to_url(&self.url),
                    user_agent: self.user_agent.clone(),
                    http_client: self.http_client.clone(),
                })
            }))
        .await
    }

    pub async fn system_version(&self, ticket_id: Uuid) -> Option<String> {
        self.with_key_settlement(ticket_id, async |keys| keys.system_version().cloned())
            .await
            .map(|v| serde_json::to_string(&v).expect("serialization should work"))
    }

    pub fn search<S: routex_api::Service>(
        &self,
        ticket: Authenticated<routex_api::Ticket<S>>,
        filters: impl IntoIterator<Item = routex_api::info::SearchFilter>,
    ) -> SearchRequest<S, C> {
        SearchRequest {
            inner: routex_api::info::Request::new(filters),
            ticket,
            client: self.clone(),
        }
    }

    pub async fn info<S: routex_api::Service>(
        &self,
        ticket: &Authenticated<routex_api::Ticket<S>>,
        connection_id: ConnectionId,
    ) -> Result<ConnectionInfo> {
        let response = self
            .execute(
                ticket,
                self.get(
                    &routex_api::info::fetch_path(&connection_id.to_string()).to_url(self.url()),
                ),
            )
            .await
            .map_err(|err| {
                if let Error::ResponseError(response) = &err
                    && response.status == StatusCode::NOT_FOUND
                {
                    Error::NotFound
                } else {
                    err
                }
            })?;

        json_decode(&response)
    }

    pub async fn execute<S: routex_api::Service>(
        &self,
        ticket: &Authenticated<routex_api::Ticket<S>>,
        request: RequestBuilder,
    ) -> Result<Bytes> {
        let ticket_id = ticket.to_data().id;

        self.with_key_settlement(ticket_id, async |keys| {
            let mut request = request.build(&ticket_id, self.user_agent.clone());

            request.headers_mut().insert(
                routex_api::headers::TICKET.clone(),
                HeaderValue::from_str(
                    &BASE64_STANDARD.encode(
                        keys.seal(ticket.as_str().as_bytes(), &ticket_id)
                            .await
                            .map_err(Error::RequestError)?,
                    ),
                )
                .expect("ASCII"),
            );

            if let Some(value) = self.redirect_uri.clone() {
                request
                    .headers_mut()
                    .insert(&routex_api::headers::REDIRECT_URI, value);
            }

            *request.body_mut() = keys
                .seal(request.body(), &ticket_id)
                .await
                .map_err(Error::RequestError)?;

            request.headers_mut().insert(
                &routex_api::headers::SESSION_ID,
                keys.session_id(&ticket_id)
                    .await
                    .map_err(Error::RequestError)?
                    .clone(),
            );

            request.headers_mut().remove(&CONTENT_LENGTH);

            let response = self.http_client.execute(request).await?;

            *self.trace_id.write().expect("poisoned") = response
                .headers
                .get(&routex_api::headers::TRACE_ID)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| BASE64_STANDARD.decode(v).ok())
                .and_then(|v| keys.unseal(&v).ok());

            if response.status.is_client_error() || response.status.is_server_error() {
                Err(Response {
                    body: keys
                        .unseal(&response.body)
                        .map_or(response.body, Into::into),
                    ..response
                }
                .into())
            } else {
                Ok(if response.body.is_empty() {
                    response.body
                } else {
                    keys.unseal(&response.body)
                        .map_err(|err| Error::RequestError(anyhow!(err)))?
                        .into()
                })
            }
        })
        .await
    }

    pub fn get(&self, url: &Url) -> RequestBuilder {
        RequestBuilder::get(url)
    }

    pub fn post(&self, url: &Url, json: &impl Serialize) -> RequestBuilder {
        RequestBuilder::post(url, json)
    }

    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Trace identifier returned with the last request
    ///
    /// # Panics
    ///
    /// Panics of the internal lock is poisoned.
    pub fn trace_id(&self) -> Option<Vec<u8>> {
        self.trace_id.read().expect("poisoned").clone()
    }

    pub fn set_redirect_uri(
        &mut self,
        redirect_uri: &str,
    ) -> std::result::Result<(), InvalidHeaderValue> {
        self.redirect_uri = Some(redirect_uri.try_into()?);
        Ok(())
    }
}

#[must_use]
pub fn handle_not_found(err: Error) -> Error {
    if let Error::ResponseError(response) = &err
        && response.status == StatusCode::NOT_FOUND
    {
        Error::NotFound
    } else {
        err
    }
}

/// A ticket that contains only the service, but no other data.
#[derive(serde::Deserialize, Clone)]
pub struct ServiceOnlyTicket {
    pub service: ServiceId,
}

#[macro_export]
macro_rules! with_any_service {
    ($ticket:expr, $authenticated:ident, $block:block) => {
        match $ticket.parse::<routex_api::Authenticated<routex_client_common::ServiceOnlyTicket>>()
        {
            Ok($authenticated) => match $authenticated.to_data().service {
                routex_api::ServiceId::Accounts { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::accounts::Service
                    )
                }
                routex_api::ServiceId::CollectPayment { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::collect_payment::Service
                    )
                }
                routex_api::ServiceId::Balances { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::balances::Service
                    )
                }
                routex_api::ServiceId::Transactions { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::transactions::Service
                    )
                }
                routex_api::ServiceId::Transfer { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::transfer::Service
                    )
                }
            },
            Err(err) => Err(err.into()),
        }
    };
    ($ticket:expr, $authenticated:ident, $block:block, $service:ty) => {
        match $ticket.parse::<routex_api::Authenticated<routex_api::Ticket<$service>>>() {
            Ok($authenticated) => $block.map_err(Into::into),
            Err(err) => Err(err.into()),
        }
    };
}

#[cfg(feature = "uniffi")]
::uniffi::setup_scaffolding!();

#[cfg(feature = "error")]
#[allow(clippy::enum_variant_names)]
#[derive(thiserror::Error, Debug)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
pub enum RoutexClientError {
    #[error("Invalid redirect URI")]
    InvalidRedirectUri,

    #[error("Request error")]
    RequestError { error: String },

    #[error("Unexpected service error")]
    UnexpectedError { user_message: Option<String> },

    #[error("Canceled")]
    Canceled,

    #[error("Invalid credentials")]
    InvalidCredentials { user_message: Option<String> },

    #[error("Service blocked")]
    ServiceBlocked {
        user_message: Option<String>,
        code: Option<ServiceBlockedCode>,
    },

    #[error("Unauthorized")]
    Unauthorized { user_message: Option<String> },

    #[error("Consent expired")]
    ConsentExpired { user_message: Option<String> },

    #[error("Access exceeded")]
    AccessExceeded { user_message: Option<String> },

    #[error("Period out of bounds")]
    PeriodOutOfBounds { user_message: Option<String> },

    #[error("Unsupported product")]
    UnsupportedProduct {
        reason: Option<UnsupportedProductReason>,
        user_message: Option<String>,
    },

    #[error("Payment canceled or rejected")]
    PaymentFailed {
        code: Option<PaymentErrorCode>,
        user_message: Option<String>,
    },

    #[error("Unexpected value")]
    UnexpectedValue { error: String },

    #[error("{error}")]
    TicketError {
        error: String,
        code: TicketErrorCode,
    },

    #[error("The account-servicing provider indicated a technical error")]
    ProviderError {
        code: Option<ProviderErrorCode>,
        user_message: Option<String>,
    },

    #[error("Error response")]
    ResponseError { response: String },

    #[error("Resource not found")]
    NotFound,

    #[error("The transaction is not possible without user interaction")]
    InterruptError,
}

#[cfg(feature = "error")]
impl From<Error> for RoutexClientError {
    fn from(error: Error) -> Self {
        match error {
            Error::RequestError(error) => Self::RequestError {
                error: error.to_string(),
            },
            Error::ServiceError(ServiceError::UnexpectedError { user_message, .. }) => {
                Self::UnexpectedError { user_message }
            }
            Error::ServiceError(ServiceError::Canceled { .. }) => Self::Canceled,
            Error::ServiceError(ServiceError::InvalidCredentials { user_message, .. }) => {
                Self::InvalidCredentials { user_message }
            }
            Error::ServiceError(ServiceError::ServiceBlocked {
                user_message, code, ..
            }) => Self::ServiceBlocked { user_message, code },
            Error::ServiceError(ServiceError::Unauthorized { user_message, .. }) => {
                Self::Unauthorized { user_message }
            }
            Error::ServiceError(ServiceError::ConsentExpired { user_message, .. }) => {
                Self::ConsentExpired { user_message }
            }
            Error::ServiceError(ServiceError::AccessExceeded { user_message, .. }) => {
                Self::AccessExceeded { user_message }
            }
            Error::ServiceError(ServiceError::PeriodOutOfBounds { user_message, .. }) => {
                Self::PeriodOutOfBounds { user_message }
            }
            Error::ServiceError(ServiceError::UnsupportedProduct {
                reason,
                user_message,
                ..
            }) => Self::UnsupportedProduct {
                reason,
                user_message,
            },
            Error::ServiceError(ServiceError::PaymentFailed {
                code, user_message, ..
            }) => Self::PaymentFailed { code, user_message },
            Error::ServiceError(ServiceError::UnexpectedValue { error, .. }) => {
                Self::UnexpectedValue { error }
            }
            Error::ServiceError(ServiceError::TicketError { error, code, .. }) => {
                Self::TicketError { error, code }
            }
            Error::ServiceError(ServiceError::ProviderError {
                code, user_message, ..
            }) => Self::ProviderError { code, user_message },
            Error::ServiceError(ServiceError::InterruptError { .. }) => Self::InterruptError,
            Error::ResponseError(response) => Self::ResponseError {
                response: format!("{response:?}"),
            },
            Error::NotFound => Self::NotFound,
        }
    }
}

#[cfg(feature = "error")]
impl From<jsonwebtoken::errors::Error> for RoutexClientError {
    fn from(err: jsonwebtoken::errors::Error) -> Self {
        RoutexClientError::TicketError {
            error: err.to_string(),
            code: routex_api::TicketErrorCode::Invalid,
        }
    }
}

#[cfg(feature = "uniffi")]
pub struct Ticket(String);

#[cfg(feature = "uniffi")]
impl Ticket {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "uniffi")]
uniffi::custom_newtype!(Ticket, String);

#[cfg(feature = "uniffi")]
uniffi::custom_type!(Url, String, {
    remote,
    try_lift: |val| Ok(val.parse()?),
    lower: |obj| obj.into(),
});

#[cfg(feature = "uniffi")]
uniffi::use_remote_type!(routex_api::CountryCode);

#[cfg(feature = "uniffi")]
/// Filters for the connection lookup
///
/// String filters look for the given value anywhere in the related field, case-insensitive.
#[derive(uniffi::Enum)]
pub enum SearchFilter {
    /// List of `ConnectionType`s to consider.
    Types {
        types: Vec<routex_api::info::ConnectionType>,
    },
    /// List of `CountryCode`s to consider.
    Countries { countries: Vec<CountryCode> },
    /// String filter for the provider / product name or any alias.
    Name { name: String },
    /// String filter for the BIC.
    Bic { bic: String },
    /// String filter for the (national) bank code.
    BankCode { bank_code: String },
    /// String filter for any of those fields.
    Term { term: String },
}

#[cfg(feature = "uniffi")]
impl From<SearchFilter> for routex_api::info::SearchFilter {
    fn from(filter: SearchFilter) -> Self {
        match filter {
            SearchFilter::Types { types } => routex_api::info::SearchFilter::Types(types),
            SearchFilter::Countries { countries } => {
                routex_api::info::SearchFilter::Countries(countries)
            }
            SearchFilter::Name { name } => routex_api::info::SearchFilter::Name(name),
            SearchFilter::Bic { bic } => routex_api::info::SearchFilter::Bic(bic),
            SearchFilter::BankCode { bank_code } => {
                routex_api::info::SearchFilter::BankCode(bank_code)
            }
            SearchFilter::Term { term } => routex_api::info::SearchFilter::Term(term),
        }
    }
}

#[cfg(feature = "uniffi")]
macro_rules! account_filter {
    {
        $($field:ident $type:ty)+
    } => {
        paste::paste! {
            #[derive(uniffi::Enum)]
            pub enum AccountFilter {
                $(
                    [<$field Eq>] { value: $type },
                    [<$field NotEq>] { value: $type },
                )+
                All {
                    filters: Vec<AccountFilter>,
                },
                Any {
                    filters: Vec<AccountFilter>,
                },
                Supports { service: routex_api::SupportedService },
            }

            impl From<AccountFilter> for Option<routex_api::Filter<routex_api::accounts::AccountField>> {
                fn from(filter: AccountFilter) -> Self {
                    match filter {
                        $(
                            AccountFilter::[<$field Eq>] { value } => Some(routex_api::accounts::AccountField::[<$field:snake:upper>].eq(value)),
                            AccountFilter::[<$field NotEq>] { value } => Some(routex_api::accounts::AccountField::[<$field:snake:upper>].not_eq(value)),
                        )+
                        AccountFilter::All { filters } => filters
                            .into_iter()
                            .map(Option::<routex_api::Filter<_>>::from)
                            .flatten()
                            .reduce(routex_api::Filter::and),
                        AccountFilter::Any { filters } => filters
                            .into_iter()
                            .map(Option::<routex_api::Filter<_>>::from)
                            .flatten()
                            .reduce(routex_api::Filter::or),
                        AccountFilter::Supports { service } => {
                            Some(routex_api::Account::supports(service))
                        },
                    }
                }
            }
        }
    }
}

#[cfg(feature = "uniffi")]
account_filter! {
    Iban Option<String>
    Number Option<String>
    Bic Option<String>
    BankCode Option<String>
    Currency String
    Name Option<String>
    DisplayName Option<String>
    OwnerName Option<String>
    ProductName Option<String>
    Status Option<routex_api::AccountStatus>
    Type Option<routex_api::AccountType>
}