1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
//! This is unofficial client support integration with the REST API 2.1
//! protocol. It presents various methods of implementing online payments via
//! different PayU services and is dedicated primarily to developers wanting to
//! implement the PayU payment services.

pub mod credit;
mod deserialize;
pub mod notify;
pub mod req;
pub mod res;
mod serialize;

use std::sync::Arc;

use reqwest::redirect;
use serde::{Deserialize, Serialize};

use crate::res::OrdersInfo;

macro_rules! get_client {
    ($self:expr) => {{
        #[cfg(feature = "single-client")]
        {
            $self.client.clone()
        }
        #[cfg(not(feature = "single-client"))]
        {
            Client::build_client()
        }
    }};
}

pub static SUCCESS: &str = "SUCCESS";

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Client is not authorized. No bearer token available")]
    NoToken,
    #[error("Invalid customer ip. IP 0.0.0.0 is not acceptable")]
    CustomerIp,
    #[error("{0}")]
    Io(#[from] std::io::Error),
    #[error("Total value is not sum of products price")]
    IncorrectTotal,
    #[error("{0}")]
    Reqwest(#[from] reqwest::Error),
    #[error("Buyer is required to place an order")]
    NoBuyer,
    #[error("Description is required to place an order")]
    NoDescription,
    #[error("Client is not authorized")]
    Unauthorized,
    #[error("Refund returned invalid response")]
    Refund,
    #[error("Create order returned invalid response")]
    CreateOrder,
    #[error("Failed to fetch order transactions")]
    OrderTransactions,
    #[error("Failed to fetch order details")]
    OrderDetails,
    #[error("Failed to fetch order refunds")]
    OrderRefunds,
    #[error("PayU rejected to create order with status {status_code:?}")]
    CreateFailed {
        status_code: String,
        status_desc: Option<String>,
        code: Option<String>,
        severity: Option<String>,
        code_literal: Option<CodeLiteral>,
    },
    #[error("PayU rejected to perform refund with status {status_code:?}")]
    RefundFailed {
        status_code: String,
        status_desc: Option<String>,
        code: Option<String>,
        severity: Option<String>,
        code_literal: Option<CodeLiteral>,
    },
    #[error("PayU rejected order details request with status {status_code:?}")]
    OrderDetailsFailed {
        status_code: String,
        status_desc: Option<String>,
        code: Option<String>,
        severity: Option<String>,
        code_literal: Option<CodeLiteral>,
    },
    #[error("PayU rejected order transactions details request with status {status_code:?}")]
    OrderTransactionsFailed {
        status_code: String,
        status_desc: Option<String>,
        code: Option<String>,
        severity: Option<String>,
        code_literal: Option<CodeLiteral>,
    },
    #[error("PayU returned order details but without any order")]
    NoOrderInDetails,
}

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

/// PayU internal order id
///
/// Unique order identifier
#[derive(
    Debug,
    Clone,
    serde::Deserialize,
    serde::Serialize,
    derive_more::Display,
    derive_more::From,
    derive_more::Deref,
)]
#[serde(transparent)]
pub struct OrderId(pub String);

impl OrderId {
    pub fn new<S: Into<String>>(id: S) -> Self {
        Self(id.into())
    }
}

/// PayU internal merchant id
///
/// This value is customer identifier
#[derive(
    Debug,
    serde::Deserialize,
    serde::Serialize,
    Copy,
    Clone,
    derive_more::Display,
    derive_more::From,
    derive_more::Deref,
    derive_more::Constructor,
)]
#[serde(transparent)]
pub struct MerchantPosId(pub i32);

/// Public payu OAuth client identifier  
#[derive(
    Debug,
    Clone,
    serde::Deserialize,
    serde::Serialize,
    derive_more::Display,
    derive_more::From,
    derive_more::Deref,
)]
#[serde(transparent)]
pub struct ClientId(pub String);

impl ClientId {
    pub fn new<S: Into<String>>(id: S) -> Self {
        Self(id.into())
    }
}

/// Secret payu OAuth client identifier
#[derive(
    Debug,
    Clone,
    serde::Deserialize,
    serde::Serialize,
    derive_more::Display,
    derive_more::From,
    derive_more::Deref,
)]
#[serde(transparent)]
pub struct ClientSecret(pub String);

impl ClientSecret {
    pub fn new<S: Into<String>>(id: S) -> Self {
        Self(id.into())
    }
}

/// PayU payment status.
///
/// Each payment is initially Pending and can change according to following
/// graph:
///
/// <img src="https://developers.payu.com/images/order_statusesV2-en.png">
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
    /// Payment is currently being processed.
    Pending,
    /// PayU is currently waiting for the merchant system to receive (capture)
    /// the payment. This status is set if auto-receive is disabled on the
    /// merchant system.
    WaitingForConfirmation,
    /// Payment has been accepted. PayU will pay out the funds shortly.
    Completed,
    /// Payment has been cancelled and the buyer has not been charged (no money
    /// was taken from buyer's account).
    Canceled,
}

#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
    /// refund was completed successfully
    Finalized,
    /// refund was cancelled
    Canceled,
    /// refund in progress
    Pending,
    /// PayU is currently waiting for the merchant system to receive (capture)
    /// the payment. This status is set if auto-receive is disabled on the
    /// merchant system.
    WaitingForConfirmation,
    /// Payment has been accepted. PayU will pay out the funds shortly.
    Completed,
}

#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Delivery {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Street name
    street: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Postal box number
    postal_box: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Postal code
    postal_code: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// City
    city: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Province
    state: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Two-letter country code compliant with ISO-3166.
    country_code: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Address description
    name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Recipient’s name
    recipient_name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Recipient’s e-mail address
    recipient_email: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    /// Recipient’s phone number
    recipient_phone: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct BuyerShippingAddress {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// stores the shipping address
    delivery: Option<Delivery>,
}

impl BuyerShippingAddress {
    pub fn new_with_delivery(delivery: Delivery) -> Self {
        Self {
            delivery: Some(delivery),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Buyer {
    /// Required customer e-mail
    #[serde(skip_serializing_if = "Option::is_none")]
    email: Option<String>,
    /// Required customer phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    phone: Option<String>,
    /// Required customer first name
    #[serde(skip_serializing_if = "Option::is_none")]
    first_name: Option<String>,
    /// Required customer last name
    #[serde(skip_serializing_if = "Option::is_none")]
    last_name: Option<String>,
    /// Required customer language
    #[serde(skip_serializing_if = "Option::is_none")]
    language: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    delivery: Option<BuyerShippingAddress>,
}

impl Buyer {
    pub fn new<Email, Phone, FirstName, LastName, Language>(
        email: Email,
        phone: Phone,
        first_name: FirstName,
        last_name: LastName,
        lang: Language,
    ) -> Self
    where
        Email: Into<String>,
        Phone: Into<String>,
        FirstName: Into<String>,
        LastName: Into<String>,
        Language: Into<String>,
    {
        Self {
            email: Some(email.into()),
            phone: Some(phone.into()),
            first_name: Some(first_name.into()),
            last_name: Some(last_name.into()),
            language: Some(lang.into()),
            delivery: None,
        }
    }

    pub fn email(&self) -> &str {
        self.email.as_deref().unwrap_or_default()
    }
    pub fn with_email<S>(mut self, email: S) -> Self
    where
        S: Into<String>,
    {
        self.email = Some(email.into());
        self
    }
    pub fn phone(&self) -> &str {
        self.phone.as_deref().unwrap_or_default()
    }
    pub fn with_phone<S>(mut self, phone: S) -> Self
    where
        S: Into<String>,
    {
        self.phone = Some(phone.into());
        self
    }
    pub fn first_name(&self) -> &str {
        self.first_name.as_deref().unwrap_or_default()
    }
    pub fn with_first_name<S>(mut self, first_name: S) -> Self
    where
        S: Into<String>,
    {
        self.first_name = Some(first_name.into());
        self
    }
    pub fn last_name(&self) -> &str {
        self.last_name.as_deref().unwrap_or_default()
    }
    pub fn with_last_name<S>(mut self, last_name: S) -> Self
    where
        S: Into<String>,
    {
        self.last_name = Some(last_name.into());
        self
    }
    pub fn language(&self) -> &str {
        self.language.as_deref().unwrap_or_default()
    }
    pub fn with_language<S>(mut self, language: S) -> Self
    where
        S: Into<String>,
    {
        self.language = Some(language.into());
        self
    }

    pub fn with_delivery(mut self, delivery: Delivery) -> Self {
        self.delivery = Some(BuyerShippingAddress::new_with_delivery(delivery));
        self
    }
}

pub type Price = i32;
pub type Quantity = u32;

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Product {
    pub name: String,
    #[serde(
        serialize_with = "serialize::serialize_i32",
        deserialize_with = "deserialize::deserialize_i32"
    )]
    pub unit_price: Price,
    #[serde(
        serialize_with = "serialize::serialize_u32",
        deserialize_with = "deserialize::deserialize_u32"
    )]
    pub quantity: Quantity,
    /// Product type, which can be virtual or material; (possible values true or
    /// false).
    #[serde(rename = "virtual", skip_serializing_if = "Option::is_none")]
    pub virtual_product: Option<bool>,
    /// Marketplace date from which the product (or offer) is available, ISO
    /// format applies, e.g. "2019-03-27T10:57:59.000+01:00".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub listing_date: Option<chrono::NaiveDateTime>,
}

impl Product {
    pub fn new<Name: Into<String>>(name: Name, unit_price: Price, quantity: Quantity) -> Self {
        Self {
            name: name.into(),
            unit_price,
            quantity,
            virtual_product: None,
            listing_date: None,
        }
    }

    /// Product type, which can be virtual or material; (possible values true or
    /// false).
    pub fn into_virtual(mut self) -> Self {
        self.virtual_product = Some(true);
        self
    }

    /// Product type, which can be virtual or material; (possible values true or
    /// false).
    pub fn non_virtual(mut self) -> Self {
        self.virtual_product = Some(false);
        self
    }

    /// Marketplace date from which the product (or offer) is available, ISO
    /// format applies, e.g. "2019-03-27T10:57:59.000+01:00".
    pub fn with_listing_date(mut self, listing_date: chrono::NaiveDateTime) -> Self {
        self.listing_date = Some(listing_date);
        self
    }

    fn erase_listing_date(mut self) -> Self {
        self.listing_date = None;
        self
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ShoppingCart {
    /// Section containing data of shipping method.
    #[serde(skip_serializing_if = "Option::is_none")]
    shopping_method: Option<ShoppingMethod>,
    /// Section containing data about ordered products.
    /// > Note: product objects in the <shoppingCart.products> section do not
    /// > have a listingDate field
    #[serde(skip_serializing_if = "Option::is_none")]
    products: Option<Vec<Product>>,
    /// Submerchant identifier. This field should be consistent with field
    /// extCustomerId in shoppingCarts section when order is placed in
    /// marketplace.
    ext_customer_id: String,
}

impl ShoppingCart {
    pub fn new<ExtCustomerId, Products>(ext_customer_id: ExtCustomerId) -> Self
    where
        ExtCustomerId: Into<String>,
    {
        Self {
            shopping_method: None,
            ext_customer_id: ext_customer_id.into(),
            products: None,
        }
    }

    pub fn new_with_products<ExtCustomerId, Products>(
        ext_customer_id: ExtCustomerId,
        products: Products,
    ) -> Self
    where
        ExtCustomerId: Into<String>,
        Products: Iterator<Item = Product>,
    {
        Self {
            shopping_method: None,
            ext_customer_id: ext_customer_id.into(),
            products: Some(products.map(Product::erase_listing_date).collect()),
        }
    }

    pub fn with_products<Products>(mut self, products: Products) -> Self
    where
        Products: Iterator<Item = Product>,
    {
        self.products = Some(products.map(Product::erase_listing_date).collect());
        self
    }

    /// Section containing data of shipping method.
    pub fn shopping_method(&self) -> &Option<ShoppingMethod> {
        &self.shopping_method
    }

    /// Section containing data about ordered products.
    /// > Note: product objects in the <shoppingCart.products> section do not
    /// > have a listingDate field
    pub fn products(&self) -> &Option<Vec<Product>> {
        &self.products
    }

    /// Submerchant identifier. This field should be consistent with field
    /// extCustomerId in shoppingCarts section when order is placed in
    /// marketplace.
    pub fn ext_customer_id(&self) -> &String {
        &self.ext_customer_id
    }
}

/// Type of shipment
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ShoppingMethodType {
    Courier,
    CollectionPointPickup,
    ParcelLocker,
    StorePickup,
}

/// Delivery address
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Address {
    /// The full name of the pickup point, including its unique identifier, e.g.
    /// „Parcel locker POZ29A”.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub point_id: Option<String>,
    /// Street name, possibly including house and flat number.
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub street: Option<String>,
    /// Street number
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub street_no: Option<String>,
    /// Flat number
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_no: Option<String>,
    /// Postal code
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub postal_code: Option<String>,
    /// City
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub city: Option<String>,
    /// Two-letter country code compliant with ISO-3166
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country_code: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ShoppingMethod {
    /// Shipping type
    /// Recommended
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub shopping_type: Option<ShoppingMethodType>,
    /// Shipping cost
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,
    /// Section containing data about shipping address.
    /// Recommended
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Address>,
}

/// MultiUseCartToken
pub mod muct {
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, Debug)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum CardOnFile {
        /// Payment initialized by the card owner who agreed to save card for
        /// future use. You can expect full authentication (3D Secure
        /// and/or CVV). If you want to use multi-use token (TOKC_)
        /// later, you have to be confident, that first payment was
        /// successful. Default value for single-use token (TOK_).
        ///
        /// In case of plain card data payments you should retrieve transaction
        /// data to obtain first TransactionId. It should be passed in
        /// payMethods.payMethod.card section for transactions marked as
        /// STANDARD, STANDARD_CARDHOLDER and STANDARD_MERCHANT;
        /// STANDARD_CARDHOLDER - payment with already saved card,
        /// initialized by the card owner. This transaction has
        /// multi-use token (TOKC_). Depending of payment parameters
        /// (e.g. high transaction amount) strong authentication can be
        /// expected (3D Secure and/or CVV). Default value for multi-use token
        /// (TOKC_);
        First,
        /// Payment with already saved card, initialized by the shop without the
        /// card owner participation. This transaction has multi-use token
        /// (TOKC_). By the definition, this payment type does not
        /// require strong authentication. You cannot use it if FIRST
        /// card-on-file payment failed.
        StandardMerchant,
    }

    #[derive(Serialize, Deserialize, Debug)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    pub enum Recurring {
        /// Payment initialized by the card owner who agreed to save card for
        /// future use in recurring plan. You can expect full authentication (3D
        /// Secure and/or CVV). If you want to use multi-use token (TOKC_)
        /// later, you have to be confident, that   first recurring
        /// payment was successful.
        First,
        /// Subsequent recurring payment (user is not present). This transaction
        /// has multi use token (TOKC_). You cannot use it if FIRST recurring
        /// payment failed.
        Standard,
    }

    #[derive(Serialize, Deserialize, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct MultiUseCartToken {
        /// Information about party initializing order:
        ///
        /// * `FIRST` - payment initialized by the card owner who agreed to save
        ///   card for future use. You can expect full authentication (3D Secure
        ///   and/or CVV). If you want to use multi-use token (TOKC_) later, you
        ///   have to be confident, that first payment was successful. Default
        ///   value for single-use token (TOK_).
        ///
        ///   In case of plain card data payments you should retrieve
        /// transaction   data to obtain first TransactionId. It should
        /// be passed in   payMethods.payMethod.card section for
        /// transactions marked as STANDARD,   STANDARD_CARDHOLDER and
        /// STANDARD_MERCHANT; STANDARD_CARDHOLDER -   payment with
        /// already saved card, initialized by the card owner. This
        ///   transaction has multi-use token (TOKC_). Depending of payment
        ///   parameters (e.g. high transaction amount) strong authentication
        /// can be   expected (3D Secure and/or CVV). Default value for
        /// multi-use token   (TOKC_);
        /// * `STANDARD_MERCHANT` - payment with already saved card, initialized
        ///   by the shop without the card owner participation. This transaction
        ///   has multi-use token (TOKC_). By the definition, this payment type
        ///   does not require strong authentication. You cannot use it if FIRST
        ///   card-on-file payment failed.
        ///
        /// `cardOnFile` parameter cannot be used with recurring parameter.
        pub card_on_file: CardOnFile,
        /// Marks the order as recurring payment.
        ///
        /// * `FIRST` - payment initialized by the card owner who agreed to save
        ///   card for future use in recurring plan. You can expect full
        ///   authentication (3D Secure and/or CVV). If you want to use
        ///   multi-use token (TOKC_) later, you have to be confident, that
        ///   first recurring payment was successful.
        /// * `STANDARD` - subsequent recurring payment (user is not present).
        ///   This transaction has multi use token (TOKC_). You cannot use it if
        ///   FIRST recurring payment failed.
        ///
        /// `recurring` parameter cannot be used with cardOnFile parameter.
        pub recurring: Recurring,
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentType {
    Pbl,
    CardToken,
    Installments,
}

/// Wrapper around pay method. It's used only for deserializing notifications
///
/// # Examples
///
/// ```
/// # use pay_u::PayMethod;
/// let method: PayMethod = serde_json::from_str(r#"
///     {
///         "type": "INSTALLMENTS"
///     }
/// "#).unwrap();
/// ```
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayMethod {
    #[serde(rename = "type")]
    pub payment_type: PaymentType,
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Status {
    /// One of
    /// * `PENDING`: Payment is currently being processed.
    /// * `WAITING_FOR_CONFIRMATION`: PayU is currently waiting for the merchant
    ///   system to receive (capture) the payment. This status is set if
    ///   auto-receive is disabled on the merchant system.
    /// * `COMPLETED`: Payment has been accepted. PayU will pay out the funds
    ///   shortly.
    /// * `CANCELED`: Payment has been cancelled and the buyer has not been
    ///   charged (no money was taken from buyer's account).
    ///
    /// > Too prevent sending wrong status from server to PayU this field
    /// > remains String
    status_code: String,
    status_desc: Option<String>,
    code: Option<String>,
    severity: Option<String>,
    code_literal: Option<CodeLiteral>,
}

impl Status {
    /// Check if http request was successful
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::Status;
    /// let status: Status = serde_json::from_str("{\"statusCode\":\"SUCCESS\"}").unwrap();
    /// assert_eq!(status.is_success(), true);
    /// ```
    pub fn is_success(&self) -> bool {
        self.status_code.as_str() == SUCCESS
    }

    /// Returns http status
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::Status;
    /// let status: Status = serde_json::from_str("{\"statusCode\":\"SUCCESS\"}").unwrap();
    /// assert_eq!(status.status_code(), "SUCCESS");
    /// ```
    pub fn status_code(&self) -> &str {
        &self.status_code
    }

    pub fn status_desc(&self) -> Option<&str> {
        self.status_desc.as_deref()
    }

    pub fn code(&self) -> Option<&str> {
        self.code.as_deref()
    }

    pub fn severity(&self) -> Option<&str> {
        self.severity.as_deref()
    }

    pub fn code_literal(&self) -> Option<&CodeLiteral> {
        self.code_literal.as_ref()
    }
}

#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StatusCode {
    ErrorValueMissing,
    OpenpayuBusinessError,
    OpenpayuErrorValueInvalid,
    OpenpayuErrorInternal,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CodeLiteral {
    /// Request lacks "refund" object.
    MissingRefundSection,

    /// Transaction has not been finalized
    TransNotEnded,

    /// Lack of funds in account
    NoBalance,

    /// Refund amount exceeds transaction amount
    AmountToBig,

    /// Refund value is too small
    AmountToSmall,

    /// Refunds have been disabled
    RefundDisabled,

    /// Too many refund attempts have been made
    RefundToOften,

    /// Refund was already created
    Paid,

    /// Unknown error
    UnknownError,

    /// extRefundId was re-used and other params do not match the values
    /// sent during the first call.
    RefundIdempotencyMismatch,

    /// Shop billing has not yet been completed
    TransBillingEntriesNotCompleted,

    /// The available time for refund has passed.
    TransTooOld,

    /// Transaction amount that remains after refund creation will be too
    /// small to make another refund.
    RemainingTransAmountTooSmall,

    #[serde(other)]
    /// Implementation changed
    Unknown,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Prop {
    pub name: String,
    pub value: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Refund {
    pub refund_id: String,
    pub ext_refund_id: Option<String>,
    pub amount: String,
    pub currency_code: String,
    pub description: String,
    pub creation_date_time: String,
    pub status: String,
    pub status_date_time: String,
}

pub struct Client {
    sandbox: bool,
    merchant_pos_id: MerchantPosId,
    client_id: ClientId,
    client_secret: ClientSecret,
    bearer: Option<String>,
    bearer_expires_at: chrono::DateTime<chrono::Utc>,
    #[cfg(feature = "single-client")]
    client: Arc<reqwest::Client>,
}

impl Client {
    /// Create new PayU client
    pub fn new(
        client_id: ClientId,
        client_secret: ClientSecret,
        merchant_pos_id: MerchantPosId,
    ) -> Self {
        #[cfg(feature = "single-client")]
        {
            Self {
                bearer: None,
                sandbox: false,
                merchant_pos_id,
                client_id,
                client_secret,
                bearer_expires_at: chrono::Utc::now(),
                client: Arc::new(Self::build_client()),
            }
        }
        #[cfg(not(feature = "single-client"))]
        {
            Self {
                bearer: None,
                sandbox: false,
                merchant_pos_id,
                client_id,
                client_secret,
                bearer_expires_at: chrono::Utc::now(),
            }
        }
    }

    /// All operation will be performed in sandbox PayU environment
    ///
    /// Examples:
    ///
    /// ```
    /// # use pay_u::*;
    ///
    /// async fn test() {
    ///     let client_id = ClientId::new(std::env::var("PAYU_CLIENT_ID").unwrap());
    ///     let client_secret = ClientSecret::new(std::env::var("PAYU_CLIENT_SECRET").unwrap());
    ///     let merchant_id = std::env::var("PAYU_CLIENT_MERCHANT_ID").unwrap().parse::<i32>().map(MerchantPosId::from).unwrap();
    ///     let mut client = Client::new(client_id, client_secret, merchant_id).sandbox();
    /// }
    /// ```
    pub fn sandbox(mut self) -> Self {
        self.sandbox = true;
        self
    }

    /// Set your own bearer key
    ///
    /// Examples:
    ///
    /// ```
    /// # use pay_u::*;
    ///
    /// async fn test() {
    ///     let client_id = ClientId::new(std::env::var("PAYU_CLIENT_ID").unwrap());
    ///     let client_secret = ClientSecret::new(std::env::var("PAYU_CLIENT_SECRET").unwrap());
    ///     let merchant_id = std::env::var("PAYU_CLIENT_MERCHANT_ID").unwrap().parse::<i32>().map(MerchantPosId::from).unwrap();
    ///     let mut client = Client::new(client_id, client_secret, merchant_id).with_bearer("a89sdhas9d8yasd8", 9_999_999);
    /// }
    /// ```
    pub fn with_bearer<Bearer: Into<String>>(mut self, bearer: Bearer, expires_in: i64) -> Self {
        self.bearer = Some(bearer.into());
        self.bearer_expires_at = chrono::Utc::now() + chrono::Duration::seconds(expires_in);
        self
    }

    /// Create new order in PayU
    ///
    /// ### IMPORTANT:
    /// Do not follow redirect for any reason. Location points to
    /// payment page which is useless in this context
    ///
    /// ### IMPORTANT:
    /// Do not use rustls. It'll freeze application!
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use pay_u::*;
    /// async fn pay() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .sandbox()
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000);
    ///     let res = client
    ///         .create_order(
    ///                 req::OrderCreate::build(
    ///                     Buyer::new("john.doe@example.com", "654111654", "John", "Doe", "pl"),
    ///                     "127.0.0.1",
    ///                     "PLN",
    ///                     "Some description"
    ///                 ).expect("All fields must be valid")
    ///                 .with_notify_url("https://your.eshop.com/notify")
    ///                 .with_description("Replace description")
    ///                 .with_products([
    ///                     Product::new("Wireless Mouse for Laptop", 15000, 1),
    ///                     Product::new("HDMI cable", 6000, 1),
    ///                 ].into_iter()),
    ///             )
    ///             .await;
    /// }
    /// ```
    pub async fn create_order(&mut self, order: req::OrderCreate) -> Result<res::CreateOrder> {
        self.authorize().await?;
        if order.total_amount
            != order
                .products
                .iter()
                .fold(0, |memo, p| memo + (p.unit_price * p.quantity as i32))
        {
            return Err(Error::IncorrectTotal);
        }

        if order.buyer().is_none() {
            return Err(Error::NoBuyer);
        }

        if order.description().trim().is_empty() {
            return Err(Error::NoDescription);
        }

        let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
        let path = format!("{}/orders", self.base_url());
        let client = get_client!(self);
        let text = client
            .post(path)
            .bearer_auth(bearer)
            .json(&order.with_merchant_pos_id(self.merchant_pos_id))
            .send()
            .await?
            .text()
            .await?;
        log::trace!("Response: {}", text);
        let res: res::CreateOrder = serde_json::from_str(&text).map_err(|e| {
            log::error!("{e:?}");
            Error::CreateOrder
        })?;
        if !res.status.is_success() {
            let Status {
                status_code,
                status_desc,
                code,
                severity,
                code_literal,
            } = res.status;
            return Err(Error::CreateFailed {
                status_desc,
                status_code,
                code,
                severity,
                code_literal,
            });
        }
        Ok(res)
    }

    /// The PayU system fully supports refunds for processed payments, the
    /// balance of which is transferred directly to the buyer’s account.
    ///
    /// > For „PayU | Pay later” payment method funds are transferred to a
    /// > credit provider.
    ///
    /// You can process refund requests as either full or partial. For partial
    /// refunds, always specify the amount in the lowest unit of a given
    /// currency, which must be the same currency as the initial order (np. for
    /// Poland lowest currency unit is “grosz” so 10 pln should be given as
    /// 1000).
    ///
    /// You can send several partial refund requests for each single order. The
    /// total value of the requests must not exceed the order value.
    ///
    /// The payu system allows multiple partial refunds to be executed at the
    /// same time. To do so, the extRefundId parameter must be sent in the
    /// request. In situations where partial refunds will not be executed more
    /// than once per second, the extRefundId parameter is not required.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::*;
    /// async fn partial_refund() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000)
    ///         .sandbox();
    ///     let res = client
    ///         .refund(
    ///             OrderId::new("H9LL64F37H160126GUEST000P01"),
    ///             req::Refund::new("Refund", Some(1000)),
    ///         )
    ///         .await;
    /// }
    /// async fn full_refund() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000)
    ///         .sandbox();
    ///     let res = client
    ///         .refund(
    ///             OrderId::new("H9LL64F37H160126GUEST000P01"),
    ///             req::Refund::new("Refund", None),
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn refund(
        &mut self,
        order_id: OrderId,
        refund: req::Refund,
    ) -> Result<res::RefundDetails> {
        #[derive(Serialize, Debug)]
        #[serde(rename_all = "camelCase")]
        struct RefundWrapper {
            refund: req::Refund,
        }

        self.authorize().await?;
        if refund.description().trim().is_empty() {
            return Err(Error::NoDescription);
        }

        let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
        let path = format!("{}/orders/{}/refunds", self.base_url(), order_id);
        let client = get_client!(self);
        let text = client
            .post(path)
            .bearer_auth(bearer)
            .json(&RefundWrapper { refund })
            .send()
            .await?
            .text()
            .await?;
        log::trace!("Response: {}", text);
        let res: res::RefundDetails = serde_json::from_str(&text).map_err(|e| {
            log::error!("Invalid PayU response {e:?}");
            Error::Refund
        })?;
        if !res.status.is_success() {
            let Status {
                status_code,
                status_desc,
                code,
                severity,
                code_literal,
            } = res.status;
            return Err(Error::RefundFailed {
                status_desc,
                status_code,
                code,
                severity,
                code_literal,
            });
        }
        Ok(res)
    }

    /// Order details request. You may use it to completely remove `Order`
    /// persistence and use extOrderId to connect your data with PayU data.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::*;
    /// async fn order_details() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000)
    ///         .sandbox();
    ///     let res = client
    ///         .order_details(OrderId::new("H9LL64F37H160126GUEST000P01"))
    ///         .await;
    /// }
    /// ```
    pub async fn order_details(&mut self, order_id: OrderId) -> Result<res::OrderInfo> {
        self.authorize().await?;
        let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
        let path = format!("{}/orders/{}", self.base_url(), order_id);
        let client = get_client!(self);
        let text = client
            .get(path)
            .bearer_auth(bearer)
            .send()
            .await?
            .text()
            .await?;
        log::trace!("Response: {}", text);
        dbg!(&text);
        let mut res: OrdersInfo = serde_json::from_str(&text).map_err(|e| {
            log::error!("{e:?}");
            dbg!(e);
            Error::OrderDetails
        })?;
        if !res.status.is_success() {
            let Status {
                status_code,
                status_desc,
                code,
                severity,
                code_literal,
            } = res.status;
            return Err(Error::OrderDetailsFailed {
                status_code,
                status_desc,
                code,
                severity,
                code_literal,
            });
        }
        Ok(res::OrderInfo {
            order: if res.orders.is_empty() {
                return Err(Error::NoOrderInDetails);
            } else {
                res.orders.remove(0)
            },
            status: res.status,
            properties: res.properties,
        })
    }

    /// The transaction retrieve request message enables you to retrieve the
    /// details of transactions created for an order.
    ///
    /// Using this endpoint is extremely useful if you would like to get bank
    /// account details or card details.
    ///
    /// > Please note that although card details are available right after
    /// > transaction has been processed, the bank details may be available
    /// > either after few minutes or on the next business day, depending on the
    /// > bank.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::*;
    /// async fn order_transactions() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000)
    ///         .sandbox();
    ///     let res = client
    ///         .order_transactions(OrderId::new("H9LL64F37H160126GUEST000P01"))
    ///         .await;
    /// }
    /// ```
    pub async fn order_transactions(&mut self, order_id: OrderId) -> Result<res::Transactions> {
        self.authorize().await?;
        let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
        let path = format!("{}/orders/{}/transactions", self.base_url(), order_id);
        let client = get_client!(self);
        let text = client
            .get(path)
            .bearer_auth(bearer)
            .send()
            .await?
            .text()
            .await?;
        log::trace!("Response: {}", text);
        dbg!(&text);
        serde_json::from_str(&text).map_err(|e| {
            log::error!("{e:?}");
            dbg!(e);
            Error::OrderTransactions
        })
    }

    /// The transaction retrieve request message enables you to retrieve the
    /// details of transactions created for an order.
    ///
    /// Using this endpoint is extremely useful if you would like to get bank
    /// account details or card details.
    ///
    /// > Please note that although card details are available right after
    /// > transaction has been processed, the bank details may be available
    /// > either after few minutes or on the next business day, depending on the
    /// > bank.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pay_u::*;
    /// async fn order_transactions() {
    ///     let mut client = Client::new(ClientId::new("145227"), ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"), MerchantPosId::new(300746))
    ///         .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 2000)
    ///         .sandbox();
    ///     let res = client
    ///         .order_transactions(OrderId::new("H9LL64F37H160126GUEST000P01"))
    ///         .await;
    /// }
    /// ```
    pub async fn order_refunds(&mut self, order_id: OrderId) -> Result<Vec<Refund>> {
        self.authorize().await?;
        let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
        let path = format!("{}/orders/{}/refunds", self.base_url(), order_id);
        let client = get_client!(self);
        let text = client
            .get(path)
            .bearer_auth(bearer)
            .send()
            .await?
            .text()
            .await?;
        log::trace!("Response: {}", text);
        let res::Refunds { refunds, .. } = serde_json::from_str(&text).map_err(|e| {
            log::error!("{e:?}");
            Error::OrderRefunds
        })?;
        Ok(refunds)
    }

    /// Get or refresh token
    pub async fn authorize(&mut self) -> Result<bool> {
        use chrono::{Duration, Utc};
        if Utc::now() - Duration::seconds(1) < self.bearer_expires_at {
            return Ok(true);
        }
        #[derive(Deserialize)]
        struct BearerResult {
            access_token: String,
            expires_in: i64,
        }

        let client = get_client!(self);
        let res = client.post(&format!(
            "https://secure.payu.com/pl/standard/user/oauth/authorize?grant_type=client_credentials&client_id={}&client_secret={}",
            self.client_id,
            self.client_secret
        ))
            .send()
            .await?;
        let res = res.json::<BearerResult>().await.map_err(|e| {
            log::error!("{e}");
            Error::Unauthorized
        })?;
        log::trace!("Bearer is {}", res.access_token);
        self.bearer_expires_at = Utc::now() + Duration::seconds(res.expires_in);
        self.bearer = Some(res.access_token);
        Ok(true)
    }

    fn base_url(&self) -> &str {
        if self.sandbox {
            "https://secure.snd.payu.com/api/v2_1"
        } else {
            "https://secure.payu.com/api/v2_1"
        }
    }

    fn build_client() -> reqwest::Client {
        reqwest::ClientBuilder::default()
            .user_agent("curl/7.82.0")
            .use_native_tls()
            // Do not follow redirect!
            .redirect(redirect::Policy::none())
            .connection_verbose(true)
            .build()
            .expect("Failed to create client")
    }
}

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

    fn build_client() -> Client {
        dotenv::dotenv().ok();
        Client::new(
            ClientId::new("145227"),
            ClientSecret::new("12f071174cb7eb79d4aac5bc2f07563f"),
            MerchantPosId::new(300746),
        )
        .sandbox()
        .with_bearer("d9a4536e-62ba-4f60-8017-6053211d3f47", 999999)
    }

    async fn perform_create_order(client: &mut Client) -> Result<CreateOrder> {
        client
            .create_order(
                req::OrderCreate::build(
                    Buyer::new("john.doe@example.com", "654111654", "John", "Doe", "pl"),
                    "127.0.0.1",
                    "PLN",
                    "Desc",
                )?
                .with_notify_url("https://your.eshop.com/notify")
                .with_description("RTV market")
                .with_products(
                    [
                        Product::new("Wireless Mouse for Laptop", 15000, 1),
                        Product::new("HDMI cable", 6000, 1),
                    ]
                    .into_iter(),
                ),
            )
            .await
    }

    #[tokio::test]
    async fn create_order() {
        let mut client = build_client();
        let res = perform_create_order(&mut client).await;

        if res.is_err() {
            eprintln!("create_order res is {res:?}");
        }
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn partial_refund() {
        let mut client = build_client();
        let CreateOrder { order_id, .. } = perform_create_order(&mut client)
            .await
            .expect("Failed to create");
        let res = client
            .refund(order_id, req::Refund::new("Refund", Some(10)))
            .await;

        if res.is_err() {
            eprintln!("partial_refund res is {res:?}");
        }
        assert!(matches!(res, Err(Error::RefundFailed { .. })));
    }

    #[tokio::test]
    async fn full_refund() {
        let mut client = build_client();
        let CreateOrder { order_id, .. } = perform_create_order(&mut client)
            .await
            .expect("Failed to create");
        let res = client
            .refund(order_id, req::Refund::new("Refund", None))
            .await;

        if res.is_err() {
            eprintln!("full_refund res is {res:?}");
        }
        assert!(matches!(res, Err(Error::RefundFailed { .. })));
    }

    #[tokio::test]
    async fn order_details() {
        let mut client = build_client();
        let CreateOrder { order_id, .. } = perform_create_order(&mut client)
            .await
            .expect("Failed to create");
        let res = client.order_details(order_id).await;

        if res.is_err() {
            eprintln!("order_details res is {res:?}");
        }
        assert!(matches!(res, Ok(res::OrderInfo { .. })));
    }

    #[tokio::test]
    async fn order_transactions() {
        let mut client = build_client();
        let CreateOrder { order_id, .. } = perform_create_order(&mut client)
            .await
            .expect("Failed to create");
        let res = client.order_transactions(order_id).await;
        if res.is_err() {
            eprintln!("order_transactions res is {res:?}");
        }
        assert!(matches!(res, Err(Error::OrderTransactions)));
    }

    #[test]
    fn check_accepted_refund_json() {
        let res = serde_json::from_str::<res::RefundDetails>(include_str!(
            "../tests/responses/accepted_refund.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_cancel_json() {
        let res = serde_json::from_str::<notify::StatusUpdate>(include_str!(
            "../tests/responses/cancel.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_completed_cart_token_json() {
        let res = serde_json::from_str::<notify::StatusUpdate>(include_str!(
            "../tests/responses/completed_cart_token.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_completed_installments_json() {
        let res = serde_json::from_str::<notify::StatusUpdate>(include_str!(
            "../tests/responses/completed_installments.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_completed_pbl_json() {
        let res = serde_json::from_str::<notify::StatusUpdate>(include_str!(
            "../tests/responses/completed_pbl.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_refund_json() {
        let res = serde_json::from_str::<notify::RefundUpdate>(include_str!(
            "../tests/responses/refund.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_rejection_json() {
        let res = serde_json::from_str::<res::RefundDetails>(include_str!(
            "../tests/responses/rejection.json"
        ));
        assert!(res.is_ok());
    }
    #[test]
    fn check_custom_literal_json() {
        let res = serde_json::from_str::<res::RefundDetails>(include_str!(
            "../tests/responses/custom_code_literal.json"
        ));
        assert!(res.is_ok());
    }
}