versa 1.9.0-rc3

Versa types and utilities for developing Versa client applications in Rust
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
//! Core protocol types for Versa communication.
//!
//! This module contains the fundamental types used in the Versa Protocol for
//! communication between senders (merchants) and receivers (inbox providers).
//!
//! ## Key Types
//!
//! - [`VersaMode`]: Environment mode (prod/test) for Versa operations
//! - [`TransactionHandles`]: Identifiers for routing receipts to the correct receivers
//! - [`ReceiptRegistrationRequest`]/[`ReceiptRegistrationResponse`]: Receipt registration flow
//! - [`Receiver`]/[`ReceiverInstruction`]: Receiver endpoint information
//! - [`Sender`]: Merchant/sender information with branding details
//! - [`Checkout`]: Receipt checkout information for receivers
//!
//! ## Submodules
//!
//! - [`customer_registration`]: Customer email verification and registration
//! - [`webhook`]: Webhook delivery payloads and events
//! - [`misuse`]: Misuse reporting functionality

use serde::{Deserialize, Serialize};
use std::fmt;
use webhook::TransactionEvent;

pub mod customer_registration;
pub mod event;
pub mod misuse;
pub mod webhook;

use std::hash::{Hash, Hasher};

#[cfg(feature = "diesel")]
use std::io::Write;

#[cfg(feature = "diesel")]
use diesel::deserialize::{self, FromSql, FromSqlRow};
#[cfg(feature = "diesel")]
use diesel::prelude::*;
#[cfg(feature = "diesel")]
use diesel::serialize::{self, IsNull, Output, ToSql};
#[cfg(feature = "diesel")]
use diesel::{expression::AsExpression, sql_types::Text};

#[cfg(feature = "diesel")]
use diesel::mysql::{Mysql, MysqlValue};

use crate::protocol::customer_registration::HandleType;
use crate::protocol::event::{EventType, InitialEventType, UpdateEventType};

/// Receiver category classification
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiverCategory {
  /// Expense management receivers
  Expense,
  /// Firehose data receivers
  Firehose,
  /// Duty of care receivers
  DutyOfCare,
}

/// Filter for querying receivers
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiverFilter {
  /// Filter by receiver categories
  Category(Vec<ReceiverCategory>),
  /// Filter by regions
  Region(Vec<String>),
}

/// Public organization information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PublicOrg {
  /// Organization ID
  pub id: String,
  /// Organization name
  pub name: String,
  /// Legal name if different from display name
  pub legal_name: Option<String>,
  /// URL-friendly slug
  pub slug: String,
  /// Organization website
  pub website: String,
  /// Logo URL
  pub logo: Option<String>,
  /// Brand color in hex format
  pub brand_color: Option<String>,
  /// Stock ticker symbol
  pub stock_symbol: Option<String>,
  /// Twitter handle
  pub twitter: Option<String>,
  /// International Securities Identification Number
  pub isin: Option<String>,
  /// Legal Entity Identifier
  pub lei: Option<String>,
  /// North American Industry Classification System code
  pub naics: Option<String>,
  /// VAT registration number
  pub vat_number: Option<String>,
}

/// Information about how a receiver handles transactions
#[derive(Debug, Serialize, Deserialize)]
pub struct Handling {
  /// Whether the sender is registered with this receiver
  pub sender_registered: bool,
  /// Whether the receiver is registered in the system
  pub receiver_registered: bool,
}

/// Result of a receiver query
#[derive(Debug, Serialize, Deserialize)]
pub struct ReceiverQueryResult {
  /// Organization information
  pub org: PublicOrg,
  /// Receiver category
  pub category: ReceiverCategory,
  /// Handling information if transaction handles were provided
  pub handling: Option<Handling>,
}

/// Request body for querying receivers
#[derive(Debug, Deserialize, Serialize)]
pub struct ReceiverQueryRequest {
  /// Optional filters to apply
  pub filters: Option<Vec<ReceiverFilter>>,
  /// Optional transaction handles to check handling status
  pub handles: Option<TransactionHandles>,
}

/// Response from receiver query
#[derive(Debug, Serialize, Deserialize)]
pub struct ReceiverQueryResponse {
  /// The mode of the query (prod/test)
  pub mode: VersaMode,
  /// List of receivers matching the query
  pub receivers: Vec<ReceiverQueryResult>,
}

/// Environment mode for Versa operations.
///
/// Determines whether operations are performed in production or test mode.
/// Test mode is useful for development and testing without affecting real data.
///
/// # Example
///
/// ```rust
/// use versa::protocol::VersaMode;
///
/// let mode = VersaMode::Test;
/// assert_eq!(mode.to_string(), "test");
/// ```
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(
  feature = "diesel",
  derive(diesel::expression::AsExpression, FromSqlRow)
)]
#[cfg_attr(feature = "diesel", diesel(sql_type = Text))]
pub enum VersaMode {
  /// Production environment - real receipts and transactions
  Prod,
  /// Test environment - for development and testing
  Test,
}

pub type VersaEnv = VersaMode;

impl fmt::Display for VersaMode {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let state = match self {
      VersaMode::Prod => "prod",
      VersaMode::Test => "test",
    };
    write!(f, "{}", state)
  }
}

#[cfg(feature = "diesel")]
impl ToSql<Text, Mysql> for VersaMode {
  fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Mysql>) -> diesel::serialize::Result {
    out.write_all(&*self.to_string().as_bytes())?;
    Ok(IsNull::No)
  }
}

#[cfg(feature = "diesel")]
impl FromSql<Text, Mysql> for VersaMode {
  fn from_sql(bytes: MysqlValue<'_>) -> diesel::deserialize::Result<Self> {
    match bytes.as_bytes() {
      b"prod" => Ok(VersaMode::Prod),
      b"test" => Ok(VersaMode::Test),
      _ => Err("Unrecognized VersaMode enum variant".into()),
    }
  }
}

/// Identifiers for routing receipts to the correct receivers.
///
/// Transaction handles help the Versa registry determine which receivers
/// should get a copy of a receipt. Multiple handles can be provided to
/// ensure proper delivery.
///
/// # Example
///
/// ```rust
/// use versa::protocol::TransactionHandles;
///
/// let handles = TransactionHandles::new()
///     .with_customer_email("customer@example.com".to_string())
///     .with_merchant_user_code("USER123".to_string());
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TransactionHandles {
  /// Customer's email address
  pub customer_email: Option<String>,
  /// Domain of the customer's email (e.g., "example.com")
  pub customer_email_domain: Option<String>,
  /// Merchant's group code for multi-location businesses
  pub merchant_group_code: Option<String>,
  /// Merchant's user/customer code
  pub merchant_user_code: Option<String>,
  /// EXPERIMENTAL - Legacy client IDs
  pub versa_client_ids: Option<Vec<String>>,
  /// Organization IDs that should receive this receipt
  pub versa_org_ids: Option<Vec<String>>,
}

impl TransactionHandles {
  pub fn new() -> Self {
    Self {
      customer_email: None,
      customer_email_domain: None,
      merchant_group_code: None,
      merchant_user_code: None,
      versa_client_ids: None,
      versa_org_ids: None,
    }
  }

  pub fn with_customer_email(mut self, email_address: String) -> Self {
    self.customer_email = Some(email_address);
    self
  }

  pub fn with_customer_email_domain(mut self, domain: String) -> Self {
    self.customer_email_domain = Some(domain);
    self
  }

  pub fn with_merchant_group_code(mut self, group_code: String) -> Self {
    self.merchant_group_code = Some(group_code);
    self
  }

  pub fn with_merchant_user_code(mut self, user_code: String) -> Self {
    self.merchant_user_code = Some(user_code);
    self
  }

  #[deprecated(since = "0.28.0", note = "please use `with_versa_org_ids` instead")]
  pub fn with_versa_client_ids(mut self, ids: Vec<String>) -> Self {
    self.versa_client_ids = Some(ids);
    self
  }

  pub fn with_versa_org_ids(mut self, ids: Vec<String>) -> Self {
    self.versa_org_ids = Some(ids);
    self
  }

  pub fn iter(&self) -> TransactionHandlesIter<'_> {
    TransactionHandlesIter {
      handles: self,
      position: 0,
    }
  }
}

pub struct TransactionHandlesIter<'a> {
  handles: &'a TransactionHandles,
  position: usize,
}

impl<'a> Iterator for TransactionHandlesIter<'a> {
  type Item = (&'static HandleType, &'a str);

  fn next(&mut self) -> Option<Self::Item> {
    loop {
      match self.position {
        0 => {
          self.position += 1;
          if let Some(ref value) = self.handles.customer_email {
            return Some((&HandleType::CustomerEmail, value));
          }
        }
        1 => {
          self.position += 1;
          if let Some(ref value) = self.handles.customer_email_domain {
            return Some((&HandleType::CustomerEmailDomain, value));
          }
        }
        2 => {
          self.position += 1;
          if let Some(ref value) = self.handles.merchant_group_code {
            return Some((&HandleType::MerchantGroupCode, value));
          }
        }
        3 => {
          self.position += 1;
          if let Some(ref value) = self.handles.merchant_user_code {
            return Some((&HandleType::MerchantUserCode, value));
          }
        }
        _ => return None,
      }
    }
  }
}

impl<'a> IntoIterator for &'a TransactionHandles {
  type Item = (&'static HandleType, &'a str);
  type IntoIter = TransactionHandlesIter<'a>;

  fn into_iter(self) -> Self::IntoIter {
    self.iter()
  }
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ClientMetadata {
  pub client_string: Option<String>,
}

/// Request to register a receipt with the Versa registry.
///
/// This is the first step in sending a receipt through Versa. The registry
/// will respond with encryption keys and receiver endpoints.
///
/// # Example
///
/// ```rust
/// use versa::protocol::{EventRegistrationRequest, TransactionHandles, event::EventType};
///
/// let request = EventRegistrationRequest {
///     event_type: Some(EventType::Receipt),
///     schema_version: "2.2.0".to_string(),
///     handles: Some(TransactionHandles::new()
///         .with_customer_email("customer@example.com".to_string())),
///     transaction_id: None,
///     client_metadata: None,
///     transaction_event_filter: None,
/// };
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct EventRegistrationRequest {
  /// The schema version of the receipt (e.g., "2.2.0")
  pub schema_version: String,
  /// Provide as many handles as available to ensure the receipt is routed to the correct receivers
  pub handles: Option<TransactionHandles>,
  /// The Versa Transaction ID, if updating an existing receipt
  pub transaction_id: Option<String>,
  /// Client software metadata, such as the client_string
  pub client_metadata: Option<ClientMetadata>,
  /// Specify the event type for this registration. If left blank, the registry will default to 'receipt'
  pub event_type: Option<EventType>,
  /// Filter receivers by the specific transaction event data you are prepared to send
  pub transaction_event_filter: Option<TransactionEvent>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct InitialEventRegistrationRequest {
  /// The schema version of the receipt (e.g., "2.2.0")
  pub schema_version: String,
  /// Provide as many handles as available to ensure the receipt is routed to the correct receivers
  pub handles: TransactionHandles,
  /// Client software metadata, such as the client_string
  pub client_metadata: Option<ClientMetadata>,
  /// Specify the event type for this registration
  pub event_type: InitialEventType,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct UpdateEventRegistrationRequest {
  /// The schema version of the receipt (e.g., "2.2.0")
  pub schema_version: String,
  /// The Versa Transaction ID, which is required for update events
  pub transaction_id: String,
  /// Client software metadata, such as the client_string
  pub client_metadata: Option<ClientMetadata>,
  /// Specify the event type for this registration. If left blank, the registry will default to 'receipt'
  pub event_type: UpdateEventType,
}

pub type ReceiptRegistrationRequest = EventRegistrationRequest;

/// Information about a receipt receiver.
///
/// Contains the endpoint and authentication details needed to deliver
/// receipts to a receiver. The receiver's endpoint URL and secret are
/// used to construct webhook deliveries.
#[derive(Debug, Deserialize, Serialize)]
pub struct Receiver {
  /// Versa Org ID of the receiver
  pub org_id: String,
  /// Secret key for HMAC authentication
  pub secret: String,
  /// Webhook endpoint URL
  pub endpoint_url: String,
  /// DEPRECATED: use `endpoint_url` instead
  pub address: String,
  /// DEPRECATED: use `org_id` instead
  pub client_id: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ReceiverInstruction {
  pub endpoint_url: String,
  pub event_id: String,
  pub event_type: EventType,
  pub org_id: String,
  pub org_name: String,
  pub secret: String,
  /// DEPRECATED: use `endpoint_url` instead
  pub address: String,
  /// DEPRECATED: use `org_id` instead
  pub client_id: String,
}

/// A receiver object is hashed by its client_id — the receiver address, secret, and org_id are considered constant and non-configurable.
/// It is possible for a receiver to change their address and rotate their secret with the registry,
/// in which case any Receiver records returned by said registry will contain the updated values.
/// Assembling hash sets of outdated and new receiver objects could result in unexpected behavior—do not do store or cache receivers.
impl Hash for Receiver {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.org_id.hash(state);
    self.endpoint_url.hash(state);
  }
}

impl PartialEq for Receiver {
  fn eq(&self, other: &Self) -> bool {
    self.org_id == other.org_id && self.endpoint_url == other.endpoint_url
  }
}
impl Eq for Receiver {}

impl Hash for ReceiverInstruction {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.org_id.hash(state);
    self.endpoint_url.hash(state);
    self.event_id.hash(state);
  }
}

impl PartialEq for ReceiverInstruction {
  fn eq(&self, other: &Self) -> bool {
    self.event_id == other.event_id
  }
}
impl Eq for ReceiverInstruction {}

/// Response from the Versa registry after registering a receipt.
///
/// Contains all the information needed to encrypt and deliver the receipt
/// to the appropriate receivers.
///
/// # Example
///
/// ```rust
/// # use versa::protocol::ReceiptRegistrationResponse;
/// # fn example(response: ReceiptRegistrationResponse) {
/// let (encryption_key, summary, receivers) = response.ready_for_delivery();
///
/// // Use encryption_key to encrypt the receipt
/// // Deliver to each receiver in the receivers list
/// # }
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct ReceiptRegistrationResponse {
  /// Network mode for the registration ('prod' or 'test')
  pub mode: VersaMode,
  /// Unique ID for this receipt
  pub receipt_id: String,
  /// Transaction ID for tracking
  pub transaction_id: String,
  /// List of receivers to deliver to
  pub receivers: Vec<ReceiverInstruction>,
  /// Key for encrypting the receipt; this will be retrieved by authorized receivers
  pub encryption_key: String,
  /// DEPRECATED: use `mode` instead
  pub env: VersaMode,
}

#[derive(Clone, Debug)]
pub struct ReceiptRegistrationSummary {
  pub mode: VersaMode,
  pub receipt_id: String,
  pub transaction_id: String,
}

/// Response from the Versa registry after registering a receipt.
///
/// Contains all the information needed to encrypt and deliver the receipt
/// to the appropriate receivers.
///
/// # Example
///
/// ```rust
/// # use versa::protocol::EventRegistrationResponse;
/// # fn example(response: EventRegistrationResponse) {
/// let (encryption_key, summary, receivers) = response.ready_for_delivery();
///
/// // Use encryption_key to encrypt the receipt
/// // Deliver to each receiver in the receivers list
/// # }
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct EventRegistrationResponse {
  /// Network mode for the registration ('prod' or 'test')
  pub mode: VersaMode,
  /// Unique ID for this event
  pub event_id: String,
  /// Unique ID for this receipt
  pub receipt_id: String,
  /// Transaction ID for tracking
  pub transaction_id: String,
  /// List of receivers to deliver to
  pub receivers: Vec<ReceiverInstruction>,
  /// Key for encrypting the receipt; this will be retrieved by authorized receivers
  pub encryption_key: String,
  /// DEPRECATED: use `mode` instead
  pub env: VersaMode,
}

#[derive(Clone, Debug)]
pub struct EventRegistrationSummary {
  pub mode: VersaMode,
  pub event_id: String,
  pub receipt_id: String,
  pub transaction_id: String,
}

#[derive(Clone, Debug)]
pub struct EncryptionKey(pub String);

impl From<ReceiptRegistrationSummary> for EventRegistrationSummary {
  fn from(summary: ReceiptRegistrationSummary) -> Self {
    EventRegistrationSummary {
      mode: summary.mode,
      event_id: summary.receipt_id.clone(),
      receipt_id: summary.receipt_id,
      transaction_id: summary.transaction_id,
    }
  }
}

impl EventRegistrationResponse {
  pub fn ready_for_delivery(
    self,
  ) -> (
    EncryptionKey,
    EventRegistrationSummary,
    Vec<ReceiverInstruction>,
  ) {
    let EventRegistrationResponse {
      mode,
      event_id,
      receipt_id,
      transaction_id,
      receivers,
      encryption_key,
      env: _env,
    } = self;
    let summary = EventRegistrationSummary {
      mode,
      event_id,
      receipt_id,
      transaction_id,
    };
    (EncryptionKey(encryption_key), summary, receivers)
  }
}

impl ReceiptRegistrationResponse {
  pub fn ready_for_delivery(
    self,
  ) -> (
    EncryptionKey,
    ReceiptRegistrationSummary,
    Vec<ReceiverInstruction>,
  ) {
    let ReceiptRegistrationResponse {
      mode,
      receipt_id,
      transaction_id,
      receivers,
      encryption_key,
      env: _env,
    } = self;
    let summary = ReceiptRegistrationSummary {
      mode,
      receipt_id,
      transaction_id,
    };
    (EncryptionKey(encryption_key), summary, receivers)
  }
}

// Receiver structs

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Address {
  pub street_address: Option<String>,
  pub city: Option<String>,
  pub region: Option<String>,
  pub country: String,
  pub postal_code: Option<String>,
  pub tz: Option<String>,
}

/// Information about the sender (merchant) of a receipt.
///
/// Contains branding and identification information that helps receivers
/// properly display and attribute receipts.
///
/// # Example
///
/// ```rust
/// use versa::protocol::Sender;
///
/// let sender = Sender {
///     org_id: "org_123".to_string(),
///     name: "Example Store".to_string(),
///     website: "https://example.com".to_string(),
///     brand_color: Some("#0066cc".to_string()),
///     legal_name: Some("Example Store Inc.".to_string()),
///     logo: Some("https://example.com/logo.png".to_string()),
///     vat_number: None,
///     address: None,
/// };
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Sender {
  /// Organization ID in the Versa registry
  pub org_id: String,
  /// Display name of the sender
  pub name: String,
  /// Sender's website URL
  pub website: String,
  /// Brand color in hex format (e.g., "#0066cc")
  pub brand_color: Option<String>,
  /// Legal entity name
  pub legal_name: Option<String>,
  /// Logo URL
  pub logo: Option<String>,
  /// VAT/tax number
  pub vat_number: Option<String>,
  /// Business address
  pub address: Option<Address>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Checkout {
  pub key: String,
  pub receipt_id: String,
  pub schema_version: String,
  pub transaction_id: String,
  pub sender: Option<Sender>,
  pub handles: TransactionHandles,
  pub registered_at: i64,
  pub transaction_event_index: u8,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Envelope {
  pub encrypted: String,
  pub nonce: String,
}

#[derive(Deserialize, Serialize)]
pub struct ReceiverPayload {
  pub sender_client_id: String,
  pub receipt_id: String,
  pub envelope: Envelope,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct CheckoutRequest {
  /// The receipt_id that came with the delivery
  pub receipt_id: String,
  /// Client software metadata, such as the client_string
  pub client_metadata: Option<ClientMetadata>,
}

#[cfg(test)]
mod tests {
  use crate::protocol::{customer_registration::HandleType, event::InitialEventType};

  #[test]
  fn test_versa_env_display() {
    use super::VersaMode;
    assert_eq!(VersaMode::Prod.to_string(), "prod");
    assert_eq!(VersaMode::Test.to_string(), "test");
  }

  #[test]
  fn test_hash_sets_of_receivers() {
    use super::Receiver;
    use std::collections::HashSet;
    let mut set = HashSet::new();
    set.insert(Receiver {
      address: "foobar".to_string(),
      endpoint_url: "https://example.com".to_string(),
      client_id: "versa_cid_xyz".to_string(),
      org_id: "org_aaa".to_string(),
      secret: "flargh".to_string(),
    });
    assert_eq!(set.len(), 1);
    set.insert(Receiver {
      address: "bazbat".to_string(),
      endpoint_url: "https://example.com".to_string(),
      client_id: "versa_cid_abc".to_string(),
      org_id: "org_aaa".to_string(),
      secret: "blargh".to_string(),
    });
    assert_eq!(set.len(), 1);
    assert!(set.into_iter().next().unwrap().org_id == "org_aaa");
  }

  #[test]
  fn test_transaction_handles_iter() {
    use super::TransactionHandles;

    let handles = TransactionHandles::new()
      .with_customer_email("test@example.com".to_string())
      .with_merchant_group_code("GROUP123".to_string())
      .with_versa_org_ids(vec!["org1".to_string(), "org2".to_string()]);

    let items: Vec<_> = handles.iter().collect();
    assert_eq!(items.len(), 2);
    assert_eq!(items[0], (&HandleType::CustomerEmail, "test@example.com"));
    assert_eq!(items[1], (&HandleType::MerchantGroupCode, "GROUP123"));
  }

  #[test]
  fn test_transaction_handles_into_iter() {
    use super::TransactionHandles;

    let handles = TransactionHandles::new()
      .with_customer_email_domain("example.com".to_string())
      .with_merchant_user_code("USER456".to_string());

    let items: Vec<_> = (&handles).into_iter().collect();
    assert_eq!(items.len(), 2);
    assert_eq!(items[0], (&HandleType::CustomerEmailDomain, "example.com"));
    assert_eq!(items[1], (&HandleType::MerchantUserCode, "USER456"));
  }

  #[test]
  fn test_initial_event_type_serializes_to_valid_event_type() {
    use super::event::{EventType, InitialEventType};
    use strum::IntoEnumIterator;

    // Test all InitialEventType variants can serialize/deserialize to EventType
    for update_event in InitialEventType::iter() {
      let serialized = serde_json::to_string(&update_event).unwrap();
      let deserialized_result: Result<EventType, _> = serde_json::from_str(&serialized);
      assert!(
        deserialized_result.is_ok(),
        "InitialEventType::{:?} failed to deserialize into EventType",
        update_event
      );
    }
  }
  #[test]
  fn test_update_event_type_serializes_to_valid_event_type() {
    use super::event::{EventType, UpdateEventType};
    use strum::IntoEnumIterator;

    // Test all UpdateEventType variants can serialize/deserialize to EventType
    for update_event in UpdateEventType::iter() {
      let serialized = serde_json::to_string(&update_event).unwrap();
      let deserialized_result: Result<EventType, _> = serde_json::from_str(&serialized);
      assert!(
        deserialized_result.is_ok(),
        "UpdateEventType::{:?} failed to deserialize into EventType",
        update_event
      );
    }
  }

  #[test]
  fn test_initial_event_type_from_conversion() {
    use super::event::{EventType, InitialEventType};
    use strum::IntoEnumIterator;

    // Test all InitialEventType variants convert to EventType
    for initial_event in InitialEventType::iter() {
      let event_type: EventType = initial_event.clone().into();
      // Verify the conversion maintains the same serialized representation
      let initial_serialized = serde_json::to_string(&initial_event).unwrap();
      let event_serialized = serde_json::to_string(&event_type).unwrap();
      assert_eq!(
        initial_serialized, event_serialized,
        "InitialEventType::{:?} conversion to EventType changed serialization",
        initial_event
      );
    }
  }

  #[test]
  fn test_update_event_type_from_conversion() {
    use super::event::{EventType, UpdateEventType};
    use strum::IntoEnumIterator;

    // Test all UpdateEventType variants convert to EventType
    for update_event in UpdateEventType::iter() {
      let event_type: EventType = update_event.clone().into();
      // Verify the conversion maintains the same serialized representation
      let update_serialized = serde_json::to_string(&update_event).unwrap();
      let event_serialized = serde_json::to_string(&event_type).unwrap();
      assert_eq!(
        update_serialized, event_serialized,
        "UpdateEventType::{:?} conversion to EventType changed serialization",
        update_event
      );
    }
  }

  #[test]
  fn test_event_registration_request_variants_serialize_correctly() {
    use super::event::UpdateEventType;
    use super::webhook::TransactionEvent;
    use super::{
      EventRegistrationRequest, InitialEventRegistrationRequest, TransactionHandles,
      UpdateEventRegistrationRequest,
    };

    // Test InitialEventRegistrationRequest serializes to EventRegistrationRequest
    let initial_request = InitialEventRegistrationRequest {
      schema_version: "2.2.0".to_string(),
      handles: TransactionHandles::new().with_customer_email("test@example.com".to_string()),
      client_metadata: None,
      event_type: InitialEventType::Receipt,
    };
    let serialized = serde_json::to_string(&initial_request).unwrap();
    let deserialized: EventRegistrationRequest = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.schema_version, "2.2.0");
    assert!(deserialized.handles.is_some());
    assert!(deserialized.transaction_id.is_none());

    // Test UpdateEventRegistrationRequest serializes to EventRegistrationRequest
    let update_request = UpdateEventRegistrationRequest {
      schema_version: "2.2.0".to_string(),
      transaction_id: "txn_123".to_string(),
      client_metadata: None,
      event_type: UpdateEventType::TransitRouteStatusUpdated,
    };
    let serialized = serde_json::to_string(&update_request).unwrap();
    let deserialized: EventRegistrationRequest = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.schema_version, "2.2.0");
    assert_eq!(deserialized.transaction_id, Some("txn_123".to_string()));
  }

  #[test]
  fn test_receipt_registration_summary_to_event_registration_summary() {
    use super::{EventRegistrationSummary, ReceiptRegistrationSummary, VersaMode};

    let receipt_summary = ReceiptRegistrationSummary {
      mode: VersaMode::Test,
      receipt_id: "rcpt_123".to_string(),
      transaction_id: "txn_456".to_string(),
    };

    let event_summary: EventRegistrationSummary = receipt_summary.clone().into();

    assert_eq!(event_summary.mode, VersaMode::Test);
    assert_eq!(event_summary.receipt_id, "rcpt_123");
    assert_eq!(event_summary.event_id, "rcpt_123");
    assert_eq!(event_summary.transaction_id, "txn_456");
  }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Org {
  pub id: String,
  pub name: String,
  pub slug: String,
  pub website: String,
  pub logo: Option<String>,
  pub brand_color: Option<String>,
  pub stock_symbol: Option<String>,
  pub twitter: Option<String>,
  pub isin: Option<String>,
  pub lei: Option<String>,
  pub naics: Option<String>,
  pub vat_number: Option<String>,
  pub created: i64,
}

#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CustomerRefManagedBy {
  /// This reference was configured by the sender; if the sender deregisters it, receipts matching this handle will no longer be sent to the receiver.
  Sender,
  /// This reference was configured by the receiver; the sender cannot deregister it.
  Receiver,
  /// This reference was configured by both the sender and the receiver; if the sender deregisters it, receipts matching this handle will still be sent to the receiver, unless it is also disabled by the receiving client.
  Both,
}

/// **DEPRECATED**: This struct is deprecated and will be removed in a future version.
///
/// Response from the registry for check_registry API calls. This endpoint is being
/// deprecated as part of API simplification.
#[deprecated(
  since = "1.2.0",
  note = "The CheckRegistryResponse struct is deprecated and will be removed in a future version"
)]
#[derive(Deserialize, Serialize)]
pub struct CheckRegistryResponse {
  pub mode: VersaMode,
  /// DEPRECATED: use 'mode' instead
  pub env: VersaMode,
  pub receivers: Vec<ReceiverInfo>,
}

#[deprecated(
  since = "1.2.0",
  note = "The ReceiverInfo struct is deprecated and will be removed in a future version; use ReceiverQueryResult instead"
)]
#[derive(Debug, Deserialize, Serialize)]
pub struct ReceiverInfo {
  pub client_id: String,
  pub receiver: Option<Org>,
  pub managed_by: CustomerRefManagedBy,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct AssetRegistrationResponse {
  pub asset_id: String,
}