redmine-api 0.11.4

API for the Redmine issue tracker
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
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
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
//! Redmine API
//!
//! [`Redmine Documentation`](https://www.redmine.org/projects/redmine/wiki/rest_api)
//!
//! - [x] authentication
//! - [x] pagination
//!   - [x] add Pageable instances to all types that need them
//!   - [x] figure out a way to write a general "fetch all pages" function (problem is the different key name in the wrapper)
//! - [x] impersonation
//! - [x] attachments
//! - [x] add all the wrappers I somehow missed
//!   - [x] check if admin and send_information truly are not part of the user hash in Create/UpdateUser or if the wiki docs are wrong (admin is, send_information is not)
//! - [x] test include parameters and add relevant data to the return types
//! - [x] async support
//!
//! Potential breaking changes ahead
//! - [ ] use Enum for sort column
//! - [ ] typed ids
//! - [ ] change project_id_or_name to Enum
//! - [ ] extra filter expressions I overlooked/did not know about
//! - [ ] parameters that are more flexible than they appear

pub mod attachments;
pub mod custom_fields;
pub mod enumerations;
pub mod files;
pub mod groups;
pub mod issue_categories;
pub mod issue_relations;
pub mod issue_statuses;
pub mod issues;
pub mod my_account;
pub mod news;
pub mod project_memberships;
pub mod projects;
pub mod queries;
pub mod roles;
pub mod search;
#[cfg(test)]
pub mod test_helpers;
pub mod time_entries;
pub mod trackers;
pub mod uploads;
pub mod users;
pub mod versions;
pub mod wiki_pages;

use futures::future::FutureExt as _;

use std::str::from_utf8;

use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::de::DeserializeOwned;

use reqwest::Method;
use std::borrow::Cow;

use reqwest::Url;
use tracing::{debug, error, trace};

/// main API client object (sync)
#[derive(derive_more::Debug)]
pub struct Redmine {
    /// the reqwest client we use to perform our API requests
    client: reqwest::blocking::Client,
    /// the redmine base url
    redmine_url: Url,
    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
    #[debug(skip)]
    api_key: String,
    /// the user id we want to impersonate, only works if the API key we use has admin privileges
    impersonate_user_id: Option<u64>,
}

/// main API client object (async)
#[derive(derive_more::Debug)]
pub struct RedmineAsync {
    /// the reqwest client we use to perform our API requests
    client: reqwest::Client,
    /// the redmine base url
    redmine_url: Url,
    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
    #[debug(skip)]
    api_key: String,
    /// the user id we want to impersonate, only works if the API key we use has admin privileges
    impersonate_user_id: Option<u64>,
}

/// helper function to parse the redmine URL in the environment variable
fn parse_url<'de, D>(deserializer: D) -> Result<url::Url, D::Error>
where
    D: Deserializer<'de>,
{
    let buf = String::deserialize(deserializer)?;

    url::Url::parse(&buf).map_err(serde::de::Error::custom)
}

/// used to deserialize the required options from the environment
#[derive(Debug, Clone, serde::Deserialize)]
struct EnvOptions {
    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
    redmine_api_key: String,

    /// the redmine base url
    #[serde(deserialize_with = "parse_url")]
    redmine_url: url::Url,
}

/// Return value from paged requests, includes the actual value as well as
/// pagination data
#[derive(Debug, Clone)]
pub struct ResponsePage<T> {
    /// The actual value returned by Redmine deserialized into a user provided type
    pub values: Vec<T>,
    /// The total number of values that could be returned by requesting all pages
    pub total_count: u64,
    /// The offset from the start (zero-based)
    pub offset: u64,
    /// How many entries were returned
    pub limit: u64,
}

impl Redmine {
    /// create a [Redmine] object
    ///
    /// # Errors
    ///
    /// This will return [`crate::Error::ReqwestError`] if initialization of Reqwest client is failed.
    pub fn new(
        client: reqwest::blocking::Client,
        redmine_url: url::Url,
        api_key: &str,
    ) -> Result<Self, crate::Error> {
        Ok(Self {
            client,
            redmine_url,
            api_key: api_key.to_string(),
            impersonate_user_id: None,
        })
    }

    /// create a [Redmine] object from the environment variables
    ///
    /// REDMINE_API_KEY
    /// REDMINE_URL
    ///
    /// # Errors
    ///
    /// This will return an error if the environment variables are
    /// missing or the URL can not be parsed
    pub fn from_env(client: reqwest::blocking::Client) -> Result<Self, crate::Error> {
        let env_options = envy::from_env::<EnvOptions>()?;

        let redmine_url = env_options.redmine_url;
        let api_key = env_options.redmine_api_key;

        Self::new(client, redmine_url, &api_key)
    }

    /// Sets the user id of a user to impersonate in all future API calls
    ///
    /// this requires Redmine admin privileges
    pub fn impersonate_user(&mut self, id: u64) {
        self.impersonate_user_id = Some(id);
    }

    /// returns the redmine base url
    #[must_use]
    pub fn redmine_url(&self) -> &Url {
        &self.redmine_url
    }

    /// returns the issue URL for a given issue id
    ///
    /// this is mostly for convenience since we are already storing the
    /// redmine URL and it works entirely on the client
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn issue_url(&self, issue_id: u64) -> Url {
        let Redmine { redmine_url, .. } = self;
        // we can unwrap here because we know /issues/<number>
        // parses successfully as an url fragment
        redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
    }

    /// internal method for shared logic between the methods below which
    /// diff in how they parse the response body and how often they call this
    fn rest(
        &self,
        method: reqwest::Method,
        endpoint: &str,
        parameters: QueryParams,
        mime_type_and_body: Option<(&str, Vec<u8>)>,
    ) -> Result<(reqwest::StatusCode, bytes::Bytes), crate::Error> {
        let Redmine {
            client,
            redmine_url,
            api_key,
            impersonate_user_id,
        } = self;
        let mut url = redmine_url.join(endpoint)?;
        parameters.add_to_url(&mut url);
        debug!(%url, %method, "Calling redmine");
        let req = client
            .request(method.clone(), url.clone())
            .header("x-redmine-api-key", api_key);
        let req = if let Some(user_id) = impersonate_user_id {
            req.header("X-Redmine-Switch-User", format!("{user_id}"))
        } else {
            req
        };
        let req = if let Some((mime, data)) = mime_type_and_body {
            if let Ok(request_body) = from_utf8(&data) {
                trace!("Request body (Content-Type: {}):\n{}", mime, request_body);
            } else {
                trace!(
                    "Request body (Content-Type: {}) could not be parsed as UTF-8:\n{:?}",
                    mime, data
                );
            }
            req.body(data).header("Content-Type", mime)
        } else {
            req
        };
        let result = req.send();
        if let Err(ref e) = result {
            error!(%url, %method, "Redmine send error: {:?}", e);
        }
        let result = result?;
        let status = result.status();
        let response_body = result.bytes()?;
        match from_utf8(&response_body) {
            Ok(response_body) => {
                trace!("Response body:\n{}", &response_body);
            }
            Err(e) => {
                trace!(
                    "Response body that could not be parsed as utf8 because of {}:\n{:?}",
                    &e, &response_body
                );
            }
        }
        if status.is_client_error() {
            error!(%url, %method, "Redmine status error (client error): {:?} response: {:?}", status, from_utf8(&response_body));
            return Err(crate::Error::HttpErrorResponse(status));
        } else if status.is_server_error() {
            error!(%url, %method, "Redmine status error (server error): {:?} response: {:?}", status, from_utf8(&response_body));
            return Err(crate::Error::HttpErrorResponse(status));
        }
        Ok((status, response_body))
    }

    /// use this with endpoints that have no response body, e.g. those just deleting
    /// a Redmine object
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the request
    /// body or when the web request fails
    pub fn ignore_response_body<E>(&self, endpoint: &E) -> Result<(), crate::Error>
    where
        E: Endpoint,
    {
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let parameters = endpoint.parameters();
        let mime_type_and_body = endpoint.body()?;
        self.rest(method, &url, parameters, mime_type_and_body)?;
        Ok(())
    }

    /// use this with endpoints which return a JSON response but do not support pagination
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the request body,
    /// when the web request fails or when the response can not be parsed as a JSON object
    /// into the result type
    pub fn json_response_body<E, R>(&self, endpoint: &E) -> Result<R, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + NoPagination,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let parameters = endpoint.parameters();
        let mime_type_and_body = endpoint.body()?;
        let (status, response_body) = self.rest(method, &url, parameters, mime_type_and_body)?;
        if response_body.is_empty() {
            Err(crate::Error::EmptyResponseBody(status))
        } else {
            let result = serde_json::from_slice::<R>(&response_body);
            if let Ok(ref parsed_response_body) = result {
                trace!("Parsed response body:\n{:#?}", parsed_response_body);
            }
            Ok(result?)
        }
    }

    /// use this to get a single page of a paginated JSON response
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the
    /// request body, when the web request fails, when the response can not be parsed
    /// as a JSON object, when any of the pagination keys or the value key are missing
    /// in the JSON object or when the values can not be parsed as the result type.
    pub fn json_response_body_page<E, R>(
        &self,
        endpoint: &E,
        offset: u64,
        limit: u64,
    ) -> Result<ResponsePage<R>, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let mut parameters = endpoint.parameters();
        parameters.push("offset", offset);
        parameters.push("limit", limit);
        let mime_type_and_body = endpoint.body()?;
        let (status, response_body) = self.rest(method, &url, parameters, mime_type_and_body)?;
        if response_body.is_empty() {
            Err(crate::Error::EmptyResponseBody(status))
        } else {
            let json_value_response_body: serde_json::Value =
                serde_json::from_slice(&response_body)?;
            let json_object_response_body = json_value_response_body.as_object();
            if let Some(json_object_response_body) = json_object_response_body {
                let total_count = json_object_response_body
                    .get("total_count")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let offset = json_object_response_body
                    .get("offset")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let limit = json_object_response_body
                    .get("limit")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_wrapper_key = endpoint.response_wrapper_key();
                let inner_response_body = json_object_response_body
                    .get(&response_wrapper_key)
                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
                if let Ok(ref parsed_response_body) = result {
                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
                }
                Ok(ResponsePage {
                    values: result?,
                    total_count,
                    offset,
                    limit,
                })
            } else {
                Err(crate::Error::NonObjectResponseBody(status))
            }
        }
    }

    /// use this to get the results for all pages of a paginated JSON response
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the
    /// request body, when any of the web requests fails, when the response can not be
    /// parsed as a JSON object, when any of the pagination keys or the value key are missing
    /// in the JSON object or when the values can not be parsed as the result type.
    ///
    pub fn json_response_body_all_pages<E, R>(&self, endpoint: &E) -> Result<Vec<R>, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let mut offset = 0;
        let limit = 100;
        let mut total_results = vec![];
        loop {
            let mut page_parameters = endpoint.parameters();
            page_parameters.push("offset", offset);
            page_parameters.push("limit", limit);
            let mime_type_and_body = endpoint.body()?;
            let (status, response_body) =
                self.rest(method.clone(), &url, page_parameters, mime_type_and_body)?;
            if response_body.is_empty() {
                return Err(crate::Error::EmptyResponseBody(status));
            }
            let json_value_response_body: serde_json::Value =
                serde_json::from_slice(&response_body)?;
            let json_object_response_body = json_value_response_body.as_object();
            if let Some(json_object_response_body) = json_object_response_body {
                let total_count: u64 = json_object_response_body
                    .get("total_count")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_offset: u64 = json_object_response_body
                    .get("offset")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_limit: u64 = json_object_response_body
                    .get("limit")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_wrapper_key = endpoint.response_wrapper_key();
                let inner_response_body = json_object_response_body
                    .get(&response_wrapper_key)
                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
                if let Ok(ref parsed_response_body) = result {
                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
                }
                total_results.extend(result?);
                if total_count < (response_offset + response_limit) {
                    break;
                }
                offset += limit;
            } else {
                return Err(crate::Error::NonObjectResponseBody(status));
            }
        }
        Ok(total_results)
    }

    /// use this to get the results for all pages of a paginated JSON response
    /// as an Iterator
    pub fn json_response_body_all_pages_iter<'a, 'e, 'i, E, R>(
        &'a self,
        endpoint: &'e E,
    ) -> AllPages<'i, E, R>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
        'a: 'i,
        'e: 'i,
    {
        AllPages::new(self, endpoint)
    }
}

impl RedmineAsync {
    /// create a [RedmineAsync] object
    ///
    /// # Errors
    ///
    /// This will return [`crate::Error::ReqwestError`] if initialization of Reqwest client is failed.
    pub fn new(
        client: reqwest::Client,
        redmine_url: url::Url,
        api_key: &str,
    ) -> Result<std::sync::Arc<Self>, crate::Error> {
        Ok(std::sync::Arc::new(Self {
            client,
            redmine_url,
            api_key: api_key.to_string(),
            impersonate_user_id: None,
        }))
    }

    /// create a [RedmineAsync] object from the environment variables
    ///
    /// REDMINE_API_KEY
    /// REDMINE_URL
    ///
    /// # Errors
    ///
    /// This will return an error if the environment variables are
    /// missing or the URL can not be parsed
    pub fn from_env(client: reqwest::Client) -> Result<std::sync::Arc<Self>, crate::Error> {
        let env_options = envy::from_env::<EnvOptions>()?;

        let redmine_url = env_options.redmine_url;
        let api_key = env_options.redmine_api_key;

        Self::new(client, redmine_url, &api_key)
    }

    /// Sets the user id of a user to impersonate in all future API calls
    ///
    /// this requires Redmine admin privileges
    pub fn impersonate_user(&mut self, id: u64) {
        self.impersonate_user_id = Some(id);
    }

    /// returns the redmine base url
    #[must_use]
    pub fn redmine_url(&self) -> &Url {
        &self.redmine_url
    }

    /// returns the issue URL for a given issue id
    ///
    /// this is mostly for convenience since we are already storing the
    /// redmine URL and it works entirely on the client
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn issue_url(&self, issue_id: u64) -> Url {
        let RedmineAsync { redmine_url, .. } = self;
        // we can unwrap here because we know /issues/<number>
        // parses successfully as an url fragment
        redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
    }

    /// internal method for shared logic between the methods below which
    /// diff in how they parse the response body and how often they call this
    async fn rest(
        self: std::sync::Arc<Self>,
        method: reqwest::Method,
        endpoint: &str,
        parameters: QueryParams<'_>,
        mime_type_and_body: Option<(&str, Vec<u8>)>,
    ) -> Result<(reqwest::StatusCode, bytes::Bytes), crate::Error> {
        let RedmineAsync {
            client,
            redmine_url,
            api_key,
            impersonate_user_id,
        } = self.as_ref();
        let mut url = redmine_url.join(endpoint)?;
        parameters.add_to_url(&mut url);
        debug!(%url, %method, "Calling redmine");
        let req = client
            .request(method.clone(), url.clone())
            .header("x-redmine-api-key", api_key);
        let req = if let Some(user_id) = impersonate_user_id {
            req.header("X-Redmine-Switch-User", format!("{user_id}"))
        } else {
            req
        };
        let req = if let Some((mime, data)) = mime_type_and_body {
            if let Ok(request_body) = from_utf8(&data) {
                trace!("Request body (Content-Type: {}):\n{}", mime, request_body);
            } else {
                trace!(
                    "Request body (Content-Type: {}) could not be parsed as UTF-8:\n{:?}",
                    mime, data
                );
            }
            req.body(data).header("Content-Type", mime)
        } else {
            req
        };
        let result = req.send().await;
        if let Err(ref e) = result {
            error!(%url, %method, "Redmine send error: {:?}", e);
        }
        let result = result?;
        let status = result.status();
        let response_body = result.bytes().await?;
        match from_utf8(&response_body) {
            Ok(response_body) => {
                trace!("Response body:\n{}", &response_body);
            }
            Err(e) => {
                trace!(
                    "Response body that could not be parsed as utf8 because of {}:\n{:?}",
                    &e, &response_body
                );
            }
        }
        if status.is_client_error() {
            error!(%url, %method, "Redmine status error (client error): {:?} response: {:?}", status, from_utf8(&response_body));
        } else if status.is_server_error() {
            error!(%url, %method, "Redmine status error (server error): {:?} response: {:?}", status, from_utf8(&response_body));
        }
        Ok((status, response_body))
    }

    /// use this with endpoints that have no response body, e.g. those just deleting
    /// a Redmine object
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the request
    /// body or when the web request fails
    pub async fn ignore_response_body<E>(
        self: std::sync::Arc<Self>,
        endpoint: impl EndpointParameter<E>,
    ) -> Result<(), crate::Error>
    where
        E: Endpoint,
    {
        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let parameters = endpoint.parameters();
        let mime_type_and_body = endpoint.body()?;
        self.rest(method, &url, parameters, mime_type_and_body)
            .await?;
        Ok(())
    }

    /// use this with endpoints which return a JSON response but do not support pagination
    ///
    /// you can use it with those that support pagination but they will only return the first page
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the request body,
    /// when the web request fails or when the response can not be parsed as a JSON object
    /// into the result type
    pub async fn json_response_body<E, R>(
        self: std::sync::Arc<Self>,
        endpoint: impl EndpointParameter<E>,
    ) -> Result<R, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + NoPagination,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let parameters = endpoint.parameters();
        let mime_type_and_body = endpoint.body()?;
        let (status, response_body) = self
            .rest(method, &url, parameters, mime_type_and_body)
            .await?;
        if response_body.is_empty() {
            Err(crate::Error::EmptyResponseBody(status))
        } else {
            let result = serde_json::from_slice::<R>(&response_body);
            if let Ok(ref parsed_response_body) = result {
                trace!("Parsed response body:\n{:#?}", parsed_response_body);
            }
            Ok(result?)
        }
    }

    /// use this to get a single page of a paginated JSON response
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the
    /// request body, when the web request fails, when the response can not be parsed
    /// as a JSON object, when any of the pagination keys or the value key are missing
    /// in the JSON object or when the values can not be parsed as the result type.
    pub async fn json_response_body_page<E, R>(
        self: std::sync::Arc<Self>,
        endpoint: impl EndpointParameter<E>,
        offset: u64,
        limit: u64,
    ) -> Result<ResponsePage<R>, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let mut parameters = endpoint.parameters();
        parameters.push("offset", offset);
        parameters.push("limit", limit);
        let mime_type_and_body = endpoint.body()?;
        let (status, response_body) = self
            .rest(method, &url, parameters, mime_type_and_body)
            .await?;
        if response_body.is_empty() {
            Err(crate::Error::EmptyResponseBody(status))
        } else {
            let json_value_response_body: serde_json::Value =
                serde_json::from_slice(&response_body)?;
            let json_object_response_body = json_value_response_body.as_object();
            if let Some(json_object_response_body) = json_object_response_body {
                let total_count = json_object_response_body
                    .get("total_count")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let offset = json_object_response_body
                    .get("offset")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let limit = json_object_response_body
                    .get("limit")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_wrapper_key = endpoint.response_wrapper_key();
                let inner_response_body = json_object_response_body
                    .get(&response_wrapper_key)
                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
                if let Ok(ref parsed_response_body) = result {
                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
                }
                Ok(ResponsePage {
                    values: result?,
                    total_count,
                    offset,
                    limit,
                })
            } else {
                Err(crate::Error::NonObjectResponseBody(status))
            }
        }
    }

    /// use this to get the results for all pages of a paginated JSON response
    ///
    /// # Errors
    ///
    /// This can return an error if the endpoint returns an error when creating the
    /// request body, when any of the web requests fails, when the response can not be
    /// parsed as a JSON object, when any of the pagination keys or the value key are missing
    /// in the JSON object or when the values can not be parsed as the result type.
    ///
    pub async fn json_response_body_all_pages<E, R>(
        self: std::sync::Arc<Self>,
        endpoint: impl EndpointParameter<E>,
    ) -> Result<Vec<R>, crate::Error>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
        let method = endpoint.method();
        let url = endpoint.endpoint();
        let mut offset = 0;
        let limit = 100;
        let mut total_results = vec![];
        loop {
            let mut page_parameters = endpoint.parameters();
            page_parameters.push("offset", offset);
            page_parameters.push("limit", limit);
            let mime_type_and_body = endpoint.body()?;
            let (status, response_body) = self
                .clone()
                .rest(method.clone(), &url, page_parameters, mime_type_and_body)
                .await?;
            if response_body.is_empty() {
                return Err(crate::Error::EmptyResponseBody(status));
            }
            let json_value_response_body: serde_json::Value =
                serde_json::from_slice(&response_body)?;
            let json_object_response_body = json_value_response_body.as_object();
            if let Some(json_object_response_body) = json_object_response_body {
                let total_count: u64 = json_object_response_body
                    .get("total_count")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_offset: u64 = json_object_response_body
                    .get("offset")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_limit: u64 = json_object_response_body
                    .get("limit")
                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
                    .as_u64()
                    .ok_or_else(|| {
                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
                    })?;
                let response_wrapper_key = endpoint.response_wrapper_key();
                let inner_response_body = json_object_response_body
                    .get(&response_wrapper_key)
                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
                if let Ok(ref parsed_response_body) = result {
                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
                }
                total_results.extend(result?);
                if total_count < (response_offset + response_limit) {
                    break;
                }
                offset += limit;
            } else {
                return Err(crate::Error::NonObjectResponseBody(status));
            }
        }
        Ok(total_results)
    }

    /// use this to get the results for all pages of a paginated JSON response
    /// as a Stream
    pub fn json_response_body_all_pages_stream<E, R>(
        self: std::sync::Arc<Self>,
        endpoint: impl EndpointParameter<E>,
    ) -> AllPagesAsync<E, R>
    where
        E: Endpoint + ReturnsJsonResponse + Pageable,
        R: DeserializeOwned + std::fmt::Debug,
    {
        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
        AllPagesAsync::new(self, endpoint)
    }
}

/// A trait representing a parameter value.
pub trait ParamValue<'a> {
    #[allow(clippy::wrong_self_convention)]
    /// The parameter value as a string.
    fn as_value(&self) -> Cow<'a, str>;
}

impl ParamValue<'static> for bool {
    fn as_value(&self) -> Cow<'static, str> {
        if *self { "true".into() } else { "false".into() }
    }
}

impl<'a> ParamValue<'a> for &'a str {
    fn as_value(&self) -> Cow<'a, str> {
        (*self).into()
    }
}

impl ParamValue<'static> for String {
    fn as_value(&self) -> Cow<'static, str> {
        self.clone().into()
    }
}

impl<'a> ParamValue<'a> for &'a String {
    fn as_value(&self) -> Cow<'a, str> {
        (*self).into()
    }
}

/// serialize a [`Vec<T>`] where T implements [ToString] as a string
/// of comma-separated values
impl<T> ParamValue<'static> for Vec<T>
where
    T: ToString,
{
    fn as_value(&self) -> Cow<'static, str> {
        self.iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(",")
            .into()
    }
}

/// serialize a [`&Vec<T>`](Vec<T>) where T implements [ToString] as a string
/// of comma-separated values
impl<'a, T> ParamValue<'a> for &'a Vec<T>
where
    T: ToString,
{
    fn as_value(&self) -> Cow<'a, str> {
        self.iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(",")
            .into()
    }
}

impl<'a> ParamValue<'a> for Cow<'a, str> {
    fn as_value(&self) -> Cow<'a, str> {
        self.clone()
    }
}

impl<'a, 'b: 'a> ParamValue<'a> for &'b Cow<'a, str> {
    fn as_value(&self) -> Cow<'a, str> {
        (*self).clone()
    }
}

impl ParamValue<'static> for u64 {
    fn as_value(&self) -> Cow<'static, str> {
        format!("{self}").into()
    }
}

impl ParamValue<'static> for f64 {
    fn as_value(&self) -> Cow<'static, str> {
        format!("{self}").into()
    }
}

impl ParamValue<'static> for time::OffsetDateTime {
    fn as_value(&self) -> Cow<'static, str> {
        self.format(&time::format_description::well_known::Rfc3339)
            .unwrap()
            .into()
    }
}

impl ParamValue<'static> for time::Date {
    fn as_value(&self) -> Cow<'static, str> {
        let format = time::format_description::parse("[year]-[month]-[day]").unwrap();
        self.format(&format).unwrap().into()
    }
}

/// Filter for a comparable date time filters for past
/// used for filters on created_on, updated_on fields
#[derive(Debug, Clone)]
pub enum DateTimeFilterPast {
    /// an exact match
    ExactMatch(time::OffsetDateTime),
    /// a range match (inclusive)
    Range(time::OffsetDateTime, time::OffsetDateTime),
    /// we only want values less than or equal to the parameter
    LessThanOrEqual(time::OffsetDateTime),
    /// we only want values greater than or equal to the parameter
    GreaterThanOrEqual(time::OffsetDateTime),
    /// less than n days ago
    LessThanDaysAgo(u32),
    /// more than n days ago
    MoreThanDaysAgo(u32),
    /// within the past n days
    WithinPastDays(u32),
    /// exactly n days ago
    ExactDaysAgo(u32),
    /// today
    Today,
    /// yesterday
    Yesterday,
    /// this week
    ThisWeek,
    /// last week
    LastWeek,
    /// last 2 weeks
    LastTwoWeeks,
    /// this month
    ThisMonth,
    /// last month
    LastMonth,
    /// this year
    ThisYear,
    /// unset value (NULL in DB)
    Unset,
    /// any value (NOT NULL in DB)
    Any,
}

impl std::fmt::Display for DateTimeFilterPast {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let format =
            time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z");
        match self {
            DateTimeFilterPast::ExactMatch(v) => {
                write!(
                    f,
                    "{}",
                    v.format(&format).expect(
                        "Error formatting OffsetDateTime in DateTimeFilterPast::ExactMatch"
                    )
                )
            }
            DateTimeFilterPast::Range(v_start, v_end) => {
                write!(
                    f,
                    "><{}|{}",
                    v_start.format(&format).expect(
                        "Error formatting first OffsetDateTime in DateTimeFilterPast::Range"
                    ),
                    v_end.format(&format).expect(
                        "Error formatting second OffsetDateTime in DateTimeFilterPast::Range"
                    ),
                )
            }
            DateTimeFilterPast::LessThanOrEqual(v) => {
                write!(
                    f,
                    "<={}",
                    v.format(&format).expect(
                        "Error formatting OffsetDateTime in DateTimeFilterPast::LessThanOrEqual"
                    )
                )
            }
            DateTimeFilterPast::GreaterThanOrEqual(v) => {
                write!(
                    f,
                    ">={}",
                    v.format(&format).expect(
                        "Error formatting OffsetDateTime in DateTimeFilterPast::GreaterThanOrEqual"
                    )
                )
            }
            DateTimeFilterPast::LessThanDaysAgo(d) => {
                write!(f, ">t-{}", d)
            }
            DateTimeFilterPast::MoreThanDaysAgo(d) => {
                write!(f, "<t-{}", d)
            }
            DateTimeFilterPast::WithinPastDays(d) => {
                write!(f, "><t-{}", d)
            }
            DateTimeFilterPast::ExactDaysAgo(d) => {
                write!(f, "t-{}", d)
            }
            DateTimeFilterPast::Today => {
                write!(f, "t")
            }
            DateTimeFilterPast::Yesterday => {
                write!(f, "ld")
            }
            DateTimeFilterPast::ThisWeek => {
                write!(f, "w")
            }
            DateTimeFilterPast::LastWeek => {
                write!(f, "lw")
            }
            DateTimeFilterPast::LastTwoWeeks => {
                write!(f, "l2w")
            }
            DateTimeFilterPast::ThisMonth => {
                write!(f, "m")
            }
            DateTimeFilterPast::LastMonth => {
                write!(f, "lm")
            }
            DateTimeFilterPast::ThisYear => {
                write!(f, "y")
            }
            DateTimeFilterPast::Unset => {
                write!(f, "!*")
            }
            DateTimeFilterPast::Any => {
                write!(f, "*")
            }
        }
    }
}

/// Filter options for subject and description
#[derive(Debug, Clone)]
pub enum StringFieldFilter {
    /// match exactly this value
    ExactMatch(String),
    /// match this substring of the actual value
    SubStringMatch(String),
}

impl std::fmt::Display for StringFieldFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StringFieldFilter::ExactMatch(s) => {
                write!(f, "{s}")
            }
            StringFieldFilter::SubStringMatch(s) => {
                write!(f, "~{s}")
            }
        }
    }
}

/// A filter for a custom field, consisting of its ID and a StringFieldFilter for its value.
#[derive(Debug, Clone)]
pub struct CustomFieldFilter {
    /// The ID of the custom field to filter by.
    pub id: u64,
    /// The value to filter the custom field by, using a `StringFieldFilter`.
    pub value: StringFieldFilter,
}

/// Filter for float values, supporting various comparison operators.
#[derive(Debug, Clone)]
pub enum FloatFilter {
    /// An exact match for the float value.
    ExactMatch(f64),
    /// A range match (inclusive) for two float values.
    Range(f64, f64),
    /// Values less than or equal to the specified float.
    LessThanOrEqual(f64),
    /// Values greater than or equal to the specified float.
    GreaterThanOrEqual(f64),
    /// Any value (equivalent to `> 0`).
    Any,
    /// No value (equivalent to `= 0`).
    None,
}

impl std::fmt::Display for FloatFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FloatFilter::ExactMatch(v) => write!(f, "{}", v),
            FloatFilter::Range(v_start, v_end) => write!(f, "><{}|{}", v_start, v_end),
            FloatFilter::LessThanOrEqual(v) => write!(f, "<={}", v),
            FloatFilter::GreaterThanOrEqual(v) => write!(f, ">={}", v),
            FloatFilter::Any => write!(f, "*"),
            FloatFilter::None => write!(f, "!*"),
        }
    }
}

/// Filter for integer values, supporting various comparison operators.
#[derive(Debug, Clone)]
pub enum IntegerFilter {
    /// An exact match for the integer value.
    ExactMatch(u64),
    /// A range match (inclusive) for two integer values.
    Range(u64, u64),
    /// Values less than or equal to the specified integer.
    LessThanOrEqual(u64),
    /// Values greater than or equal to the specified integer.
    GreaterThanOrEqual(u64),
    /// Any value (equivalent to `> 0`).
    Any,
    /// No value (equivalent to `= 0`).
    None,
}

impl std::fmt::Display for IntegerFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IntegerFilter::ExactMatch(v) => write!(f, "{}", v),
            IntegerFilter::Range(v_start, v_end) => write!(f, "><{}|{}", v_start, v_end),
            IntegerFilter::LessThanOrEqual(v) => write!(f, "<={}", v),
            IntegerFilter::GreaterThanOrEqual(v) => write!(f, ">={}", v),
            IntegerFilter::Any => write!(f, "*"),
            IntegerFilter::None => write!(f, "!*"),
        }
    }
}

/// Filter for tracker IDs.
#[derive(Debug, Clone)]
pub enum TrackerFilter {
    /// Match any tracker.
    Any,
    /// Match no tracker.
    None,
    /// Match a specific list of trackers.
    TheseTrackers(Vec<u64>),
    /// Match any tracker but a specific list of trackers.
    NotTheseTrackers(Vec<u64>),
}

impl std::fmt::Display for TrackerFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TrackerFilter::Any => write!(f, "*"),
            TrackerFilter::None => write!(f, "!*"),
            TrackerFilter::TheseTrackers(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
            TrackerFilter::NotTheseTrackers(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| format!("!{e}"))
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
        }
    }
}

/// Filter for activity IDs.
#[derive(Debug, Clone)]
pub enum ActivityFilter {
    /// Match any activity.
    Any,
    /// Match no activity.
    None,
    /// Match a specific list of activities.
    TheseActivities(Vec<u64>),
    /// Match any activity but a specific list of activities.
    NotTheseActivities(Vec<u64>),
}

impl std::fmt::Display for ActivityFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ActivityFilter::Any => write!(f, "*"),
            ActivityFilter::None => write!(f, "!*"),
            ActivityFilter::TheseActivities(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
            ActivityFilter::NotTheseActivities(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| format!("!{e}"))
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
        }
    }
}

/// Filter for fixed version IDs.
#[derive(Debug, Clone)]
pub enum VersionFilter {
    /// Match any version.
    Any,
    /// Match no version.
    None,
    /// Match a specific list of versions.
    TheseVersions(Vec<u64>),
    /// Match any version but a specific list of versions.
    NotTheseVersions(Vec<u64>),
}

impl std::fmt::Display for VersionFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VersionFilter::Any => write!(f, "*"),
            VersionFilter::None => write!(f, "!*"),
            VersionFilter::TheseVersions(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
            VersionFilter::NotTheseVersions(ids) => {
                let s: String = ids
                    .iter()
                    .map(|e| format!("!{e}"))
                    .collect::<Vec<_>>()
                    .join(",");
                write!(f, "{s}")
            }
        }
    }
}

/// Filter for date values, supporting various comparison operators.
#[derive(Debug, Clone)]
pub enum DateFilter {
    /// an exact match
    ExactMatch(time::Date),
    /// a range match (inclusive)
    Range(time::Date, time::Date),
    /// we only want values less than or equal to the parameter
    LessThanOrEqual(time::Date),
    /// we only want values greater than or equal to the parameter
    GreaterThanOrEqual(time::Date),
    /// less than n days ago
    LessThanDaysAgo(u32),
    /// more than n days ago
    MoreThanDaysAgo(u32),
    /// within the past n days
    WithinPastDays(u32),
    /// exactly n days ago
    ExactDaysAgo(u32),
    /// in less than n days
    InLessThanDays(u32),
    /// in more than n days
    InMoreThanDays(u32),
    /// in the next n days
    WithinFutureDays(u32),
    /// in exactly n days
    InExactDays(u32),
    /// today
    Today,
    /// yesterday
    Yesterday,
    /// tomorrow
    Tomorrow,
    /// this week
    ThisWeek,
    /// last week
    LastWeek,
    /// last 2 weeks
    LastTwoWeeks,
    /// next week
    NextWeek,
    /// this month
    ThisMonth,
    /// last month
    LastMonth,
    /// next month
    NextMonth,
    /// this year
    ThisYear,
    /// unset value (NULL in DB)
    Unset,
    /// any value (NOT NULL in DB)
    Any,
}

impl std::fmt::Display for DateFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let format = time::macros::format_description!("[year]-[month]-[day]");
        match self {
            DateFilter::ExactMatch(v) => {
                write!(
                    f,
                    "{}",
                    v.format(&format)
                        .expect("Error formatting Date in DateFilter::ExactMatch")
                )
            }
            DateFilter::Range(v_start, v_end) => {
                write!(
                    f,
                    "><{}|{}",
                    v_start
                        .format(&format)
                        .expect("Error formatting first Date in DateFilter::Range"),
                    v_end
                        .format(&format)
                        .expect("Error formatting second Date in DateFilter::Range"),
                )
            }
            DateFilter::LessThanOrEqual(v) => {
                write!(
                    f,
                    "<={}",
                    v.format(&format)
                        .expect("Error formatting Date in DateFilter::LessThanOrEqual")
                )
            }
            DateFilter::GreaterThanOrEqual(v) => {
                write!(
                    f,
                    ">={}",
                    v.format(&format)
                        .expect("Error formatting Date in DateFilter::GreaterThanOrEqual")
                )
            }
            DateFilter::LessThanDaysAgo(d) => {
                write!(f, ">t-{}", d)
            }
            DateFilter::MoreThanDaysAgo(d) => {
                write!(f, "<t-{}", d)
            }
            DateFilter::WithinPastDays(d) => {
                write!(f, "><t-{}", d)
            }
            DateFilter::ExactDaysAgo(d) => {
                write!(f, "t-{}", d)
            }
            DateFilter::InLessThanDays(d) => {
                write!(f, "<t+{}", d)
            }
            DateFilter::InMoreThanDays(d) => {
                write!(f, ">t+{}", d)
            }
            DateFilter::WithinFutureDays(d) => {
                write!(f, "><t+{}", d)
            }
            DateFilter::InExactDays(d) => {
                write!(f, "t+{}", d)
            }
            DateFilter::Today => {
                write!(f, "t")
            }
            DateFilter::Yesterday => {
                write!(f, "ld")
            }
            DateFilter::Tomorrow => {
                write!(f, "nd")
            }
            DateFilter::ThisWeek => {
                write!(f, "w")
            }
            DateFilter::LastWeek => {
                write!(f, "lw")
            }
            DateFilter::LastTwoWeeks => {
                write!(f, "l2w")
            }
            DateFilter::NextWeek => {
                write!(f, "nw")
            }
            DateFilter::ThisMonth => {
                write!(f, "m")
            }
            DateFilter::LastMonth => {
                write!(f, "lm")
            }
            DateFilter::NextMonth => {
                write!(f, "nm")
            }
            DateFilter::ThisYear => {
                write!(f, "y")
            }
            DateFilter::Unset => {
                write!(f, "!*")
            }
            DateFilter::Any => {
                write!(f, "*")
            }
        }
    }
}

/// A structure for query parameters.
#[derive(Debug, Default, Clone)]
pub struct QueryParams<'a> {
    /// the actual parameters
    params: Vec<(Cow<'a, str>, Cow<'a, str>)>,
}

impl<'a> QueryParams<'a> {
    /// Push a single parameter.
    pub fn push<'b, K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<Cow<'a, str>>,
        V: ParamValue<'b>,
        'b: 'a,
    {
        self.params.push((key.into(), value.as_value()));
        self
    }

    /// Push a single parameter.
    pub fn push_opt<'b, K, V>(&mut self, key: K, value: Option<V>) -> &mut Self
    where
        K: Into<Cow<'a, str>>,
        V: ParamValue<'b>,
        'b: 'a,
    {
        if let Some(value) = value {
            self.params.push((key.into(), value.as_value()));
        }
        self
    }

    /// Push a set of parameters.
    pub fn extend<'b, I, K, V>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = (K, V)>,
        K: Into<Cow<'a, str>>,
        V: ParamValue<'b>,
        'b: 'a,
    {
        self.params
            .extend(iter.map(|(key, value)| (key.into(), value.as_value())));
        self
    }

    /// Add the parameters to a URL.
    pub fn add_to_url(&self, url: &mut Url) {
        let mut pairs = url.query_pairs_mut();
        pairs.extend_pairs(self.params.iter());
    }
}

/// A trait for providing the necessary information for a single REST API endpoint.
pub trait Endpoint {
    /// The HTTP method to use for the endpoint.
    fn method(&self) -> Method;
    /// The path to the endpoint.
    fn endpoint(&self) -> Cow<'static, str>;

    /// Query parameters for the endpoint.
    fn parameters(&self) -> QueryParams<'_> {
        QueryParams::default()
    }

    /// The body for the endpoint.
    ///
    /// Returns the `Content-Encoding` header for the data as well as the data itself.
    ///
    /// # Errors
    ///
    /// The default implementation will never return an error
    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
        Ok(None)
    }
}

/// A trait to indicate that an endpoint is expected to return a JSON result
pub trait ReturnsJsonResponse {}

/// A trait to indicate that an endpoint requires pagination to yield all results
/// or in other words that the non-pagination API should not be used on it or one
/// might miss some results
#[diagnostic::on_unimplemented(
    message = "{Self} is an endpoint that either returns nothing or requires pagination, use `.ignore_response_body(&endpoint)`, `.json_response_body_page(&endpoint, offset, limit)` or `.json_response_body_all_pages(&endpoint)` instead of `.json_response_body(&endpoint)`"
)]
pub trait NoPagination {}

/// A trait to indicate that an endpoint is pageable.
#[diagnostic::on_unimplemented(
    message = "{Self} is an endpoint that does not implement pagination or returns nothing, use `.ignore_response_body(&endpoint)` or `.json_response_body(&endpoint)` instead of `.json_response_body_page(&endpoint, offset, limit)` or `.json_response_body_all_pages(&endpoint)`"
)]
pub trait Pageable {
    /// returns the name of the key in the response that contains the list of results
    fn response_wrapper_key(&self) -> String;
}

/// helper to parse created_on and updated_on in the correct format
/// (default time serde implementation seems to use a different format)
///
/// # Errors
///
/// This will return an error if the underlying string can not be deserialized or
/// can not be parsed as an RFC3339 date and time
pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;

    time::OffsetDateTime::parse(&s, &time::format_description::well_known::Rfc3339)
        .map_err(serde::de::Error::custom)
}

/// helper to serialize created_on and updated_on in the correct format
/// (default time serde implementation seems to use a different format)
///
/// # Errors
///
/// This will return an error if the date time can not be formatted as an RFC3339
/// date time or the resulting string can not be serialized
pub fn serialize_rfc3339<S>(t: &time::OffsetDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    let s = t
        .format(&time::format_description::well_known::Rfc3339)
        .map_err(serde::ser::Error::custom)?;

    s.serialize(serializer)
}

/// helper to parse created_on and updated_on in the correct format
/// (default time serde implementation seems to use a different format)
///
/// # Errors
///
/// This will return an error if the underlying string can not be deserialized
/// or it can not be parsed as an RFC3339 date and time
pub fn deserialize_optional_rfc3339<'de, D>(
    deserializer: D,
) -> Result<Option<time::OffsetDateTime>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = <Option<String> as Deserialize<'de>>::deserialize(deserializer)?;

    if let Some(s) = s {
        Ok(Some(
            time::OffsetDateTime::parse(&s, &time::format_description::well_known::Rfc3339)
                .map_err(serde::de::Error::custom)?,
        ))
    } else {
        Ok(None)
    }
}

/// helper to serialize created_on and updated_on in the correct format
/// (default time serde implementation seems to use a different format)
///
/// # Errors
///
/// This will return an error if the parameter can not be formatted as RFC3339
/// or the resulting string can not be serialized
pub fn serialize_optional_rfc3339<S>(
    t: &Option<time::OffsetDateTime>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if let Some(t) = t {
        let s = t
            .format(&time::format_description::well_known::Rfc3339)
            .map_err(serde::ser::Error::custom)?;

        s.serialize(serializer)
    } else {
        let n: Option<String> = None;
        n.serialize(serializer)
    }
}

/// represents an Iterator over all result pages
#[derive(Debug)]
pub struct AllPages<'i, E, R> {
    /// the redmine object to fetch data from
    redmine: &'i Redmine,
    /// the endpoint to request data from
    endpoint: &'i E,
    /// the offset to fetch next
    offset: u64,
    /// the limit for each fetch
    limit: u64,
    /// the cached total count value from the last request
    total_count: Option<u64>,
    /// the number of elements already yielded
    yielded: u64,
    /// the cached values from the last fetch that have not been
    /// consumed yet, in reverse order to allow pop to remove them
    reversed_rest: Vec<R>,
}

impl<'i, E, R> AllPages<'i, E, R> {
    /// create a new AllPages Iterator
    pub fn new(redmine: &'i Redmine, endpoint: &'i E) -> Self {
        Self {
            redmine,
            endpoint,
            offset: 0,
            limit: 100,
            total_count: None,
            yielded: 0,
            reversed_rest: Vec::new(),
        }
    }
}

impl<'i, E, R> Iterator for AllPages<'i, E, R>
where
    E: Endpoint + ReturnsJsonResponse + Pageable,
    R: DeserializeOwned + std::fmt::Debug,
{
    type Item = Result<R, crate::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(next) = self.reversed_rest.pop() {
            self.yielded += 1;
            return Some(Ok(next));
        }
        if let Some(total_count) = self.total_count
            && self.offset > total_count
        {
            return None;
        }
        match self
            .redmine
            .json_response_body_page(self.endpoint, self.offset, self.limit)
        {
            Err(e) => Some(Err(e)),
            Ok(ResponsePage {
                values,
                total_count,
                offset,
                limit,
            }) => {
                self.total_count = Some(total_count);
                self.offset = offset + limit;
                self.reversed_rest = values;
                self.reversed_rest.reverse();
                if let Some(next) = self.reversed_rest.pop() {
                    self.yielded += 1;
                    return Some(Ok(next));
                }
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if let Some(total_count) = self.total_count {
            (
                self.reversed_rest.len(),
                Some((total_count - self.yielded) as usize),
            )
        } else {
            (0, None)
        }
    }
}

/// represents an async Stream over all result pages
#[pin_project::pin_project]
pub struct AllPagesAsync<E, R> {
    /// the inner future while we are fetching new data
    #[allow(clippy::type_complexity)]
    #[pin]
    inner: Option<
        std::pin::Pin<Box<dyn futures::Future<Output = Result<ResponsePage<R>, crate::Error>>>>,
    >,
    /// the redmine object to fetch data from
    redmine: std::sync::Arc<RedmineAsync>,
    /// the endpoint to request data from
    endpoint: std::sync::Arc<E>,
    /// the offset to fetch next
    offset: u64,
    /// the limit for each fetch
    limit: u64,
    /// the cached total count value from the last request
    total_count: Option<u64>,
    /// the number of elements already yielded
    yielded: u64,
    /// the cached values from the last fetch that have not been
    /// consumed yet, in reverse order to allow pop to remove them
    reversed_rest: Vec<R>,
}

impl<E, R> std::fmt::Debug for AllPagesAsync<E, R>
where
    R: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AllPagesAsync")
            .field("redmine", &self.redmine)
            .field("offset", &self.offset)
            .field("limit", &self.limit)
            .field("total_count", &self.total_count)
            .field("yielded", &self.yielded)
            .field("reversed_rest", &self.reversed_rest)
            .finish()
    }
}

impl<E, R> AllPagesAsync<E, R> {
    /// create a new AllPagesAsync Stream
    pub fn new(redmine: std::sync::Arc<RedmineAsync>, endpoint: std::sync::Arc<E>) -> Self {
        Self {
            inner: None,
            redmine,
            endpoint,
            offset: 0,
            limit: 100,
            total_count: None,
            yielded: 0,
            reversed_rest: Vec::new(),
        }
    }
}

impl<E, R> futures::stream::Stream for AllPagesAsync<E, R>
where
    E: Endpoint + ReturnsJsonResponse + Pageable + 'static,
    R: DeserializeOwned + std::fmt::Debug + 'static,
{
    type Item = Result<R, crate::Error>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        ctx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if let Some(mut inner) = self.inner.take() {
            match inner.as_mut().poll(ctx) {
                std::task::Poll::Pending => {
                    self.inner = Some(inner);
                    std::task::Poll::Pending
                }
                std::task::Poll::Ready(Err(e)) => std::task::Poll::Ready(Some(Err(e))),
                std::task::Poll::Ready(Ok(ResponsePage {
                    values,
                    total_count,
                    offset,
                    limit,
                })) => {
                    self.total_count = Some(total_count);
                    self.offset = offset + limit;
                    self.reversed_rest = values;
                    self.reversed_rest.reverse();
                    if let Some(next) = self.reversed_rest.pop() {
                        self.yielded += 1;
                        return std::task::Poll::Ready(Some(Ok(next)));
                    }
                    std::task::Poll::Ready(None)
                }
            }
        } else {
            if let Some(next) = self.reversed_rest.pop() {
                self.yielded += 1;
                return std::task::Poll::Ready(Some(Ok(next)));
            }
            if let Some(total_count) = self.total_count
                && self.offset > total_count
            {
                return std::task::Poll::Ready(None);
            }
            self.inner = Some(
                self.redmine
                    .clone()
                    .json_response_body_page(self.endpoint.clone(), self.offset, self.limit)
                    .boxed_local(),
            );
            self.poll_next(ctx)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if let Some(total_count) = self.total_count {
            (
                self.reversed_rest.len(),
                Some((total_count - self.yielded) as usize),
            )
        } else {
            (0, None)
        }
    }
}

/// trait to allow both `&E` and `std::sync::Arc<E>` as parameters for endpoints
/// we can not just use Into because that tries to treat &Endpoint as the value E
/// and screws up our other trait bounds
///
/// if we just used Arc the users would have to change all old call sites
pub trait EndpointParameter<E> {
    /// convert the endpoint parameter into an Arc
    fn into_arc(self) -> std::sync::Arc<E>;
}

impl<E> EndpointParameter<E> for &E
where
    E: Clone,
{
    fn into_arc(self) -> std::sync::Arc<E> {
        std::sync::Arc::new(self.to_owned())
    }
}

impl<E> EndpointParameter<E> for std::sync::Arc<E> {
    fn into_arc(self) -> std::sync::Arc<E> {
        self
    }
}