redis-cloud 0.9.5

Redis Cloud REST API client library
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
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
//! Database management operations for Pro subscriptions
//!
//! This module provides comprehensive database management functionality for Redis Cloud
//! Pro subscriptions, including creation, configuration, backup, import/export, and
//! monitoring capabilities.
//!
//! # Overview
//!
//! Pro databases offer the full range of Redis Cloud features including high availability,
//! auto-scaling, clustering, modules, and advanced data persistence options. They can be
//! deployed across multiple cloud providers and regions.
//!
//! # Key Features
//!
//! - **Database Lifecycle**: Create, update, delete, and manage databases
//! - **Backup & Restore**: Automated and on-demand backup operations
//! - **Import/Export**: Import data from RDB files or other Redis instances
//! - **Modules**: Support for `RedisJSON`, `RediSearch`, `RedisGraph`, `RedisTimeSeries`, `RedisBloom`
//! - **High Availability**: Replication, auto-failover, and clustering support
//! - **Monitoring**: Metrics, alerts, and performance insights
//! - **Security**: TLS, password protection, and ACL support
//!
//! # Database Configuration Options
//!
//! - Memory limits from 250MB to 500GB+
//! - Support for Redis OSS Cluster API
//! - Data persistence: AOF, snapshot, or both
//! - Data eviction policies
//! - Replication and clustering
//! - Custom Redis versions
//!
//! # Example Usage
//!
//! ```no_run
//! use redis_cloud::{CloudClient, DatabaseHandler};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let client = CloudClient::builder()
//!     .api_key("your-api-key")
//!     .api_secret("your-api-secret")
//!     .build()?;
//!
//! let handler = DatabaseHandler::new(client);
//!
//! // List all databases in a subscription (subscription ID 123)
//! let databases = handler.get_subscription_databases(123, None, None).await?;
//!
//! // Get specific database details
//! let database = handler.get_subscription_database_by_id(123, 456).await?;
//! # Ok(())
//! # }
//! ```

use crate::types::{Link, ProcessorResponse};
use crate::{CloudClient, Result};
use async_stream::try_stream;
use futures_core::Stream;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use typed_builder::TypedBuilder;

// ============================================================================
// Models
// ============================================================================

/// `RedisLabs` Account Subscription Databases information
///
/// Response from GET /subscriptions/{subscriptionId}/databases
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountSubscriptionDatabases {
    /// Account ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_id: Option<i32>,

    /// Subscription information with nested databases array.
    /// The API returns this as an array, each element containing subscriptionId, databases, and links.
    #[serde(default, deserialize_with = "deserialize_subscription_info")]
    pub subscription: Vec<SubscriptionDatabasesInfo>,

    /// HATEOAS links for API navigation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Subscription databases info returned within `AccountSubscriptionDatabases`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionDatabasesInfo {
    /// Subscription ID
    pub subscription_id: i32,

    /// Number of databases (may not always be present)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_of_databases: Option<i32>,

    /// List of databases in this subscription
    #[serde(default)]
    pub databases: Vec<Database>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Custom deserializer that handles both object and array formats for subscription field.
/// The API returns an array, but some test mocks use an object format.
fn deserialize_subscription_info<'de, D>(
    deserializer: D,
) -> std::result::Result<Vec<SubscriptionDatabasesInfo>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<Value> = Option::deserialize(deserializer)?;

    match value {
        None => Ok(Vec::new()),
        Some(Value::Array(arr)) => {
            serde_json::from_value(Value::Array(arr)).map_err(serde::de::Error::custom)
        }
        Some(Value::Object(obj)) => {
            // Single object - wrap in array
            let item: SubscriptionDatabasesInfo =
                serde_json::from_value(Value::Object(obj)).map_err(serde::de::Error::custom)?;
            Ok(vec![item])
        }
        Some(other) => Err(serde::de::Error::custom(format!(
            "expected array or object for subscription, got {other:?}"
        ))),
    }
}

/// Optional. Expected read and write throughput for this region.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalThroughput {
    /// Specify one of the selected cloud provider regions for the subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    /// Write operations for this region per second. Default: 1000 ops/sec
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_operations_per_second: Option<i64>,

    /// Read operations for this region per second. Default: 1000 ops/sec
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_operations_per_second: Option<i64>,
}

/// Database tag update request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    /// Database tag value
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tag {
    /// Database tag key.
    pub key: String,

    /// Database tag value.
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Active-Active database flush request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CrdbFlushRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Database certificate
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseCertificate {
    /// An X.509 PEM (base64) encoded server certificate with new line characters replaced by '\n'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_certificate_pem_string: Option<String>,
}

/// Database tags update request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagsUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    /// List of database tags.
    pub tags: Vec<Tag>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Optional. This database will be a replica of the specified Redis databases, provided as a list of objects with endpoint and certificate details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseSyncSourceSpec {
    /// Redis URI of a source database. Example format: 'redis://user:password@host:port'. If the URI provided is a Redis Cloud database, only host and port should be provided. Example: '<redis://endpoint1:6379>'.
    pub endpoint: String,

    /// Defines if encryption should be used to connect to the sync source. If not set the source is a Redis Cloud database, it will automatically detect if the source uses encryption.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encryption: Option<bool>,

    /// TLS/SSL certificate chain of the sync source. If not set and the source is a Redis Cloud database, it will automatically detect the certificate to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_cert: Option<String>,
}

/// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections. If set to an empty list, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseCertificateSpec {
    /// Client certificate public key in PEM format, with new line characters replaced with '\n'.
    pub public_certificate_pem_string: String,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudTag {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// `BdbVersionUpgradeStatus`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BdbVersionUpgradeStatus {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_redis_version: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub progress: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub upgrade_status: Option<String>,
}

/// Active-Active database update local properties request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CrdbUpdatePropertiesRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    /// Optional. Updated database name. Database name is limited to 40 characters or less and must include only letters, digits, and hyphens ('-'). It must start with a letter and end with a letter or digit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Optional. When 'false': Creates a deployment plan and deploys it, updating any resources required by the plan. When 'true': creates a read-only deployment plan and does not update any resources. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_run: Option<bool>,

    /// Optional. Total memory in GB, including replication and other overhead. You cannot set both datasetSizeInGb and totalMemoryInGb.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_in_gb: Option<f64>,

    /// Optional. The maximum amount of data in the dataset for this database in GB. You cannot set both datasetSizeInGb and totalMemoryInGb. If ‘replication’ is 'true', the database’s total memory will be twice as large as the datasetSizeInGb.If ‘replication’ is false, the database’s total memory will be the datasetSizeInGb value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dataset_size_in_gb: Option<f64>,

    /// Optional. Support Redis [OSS Cluster API](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#oss-cluster-api). Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    pub support_oss_cluster_api: Option<bool>,

    /// Optional. If set to 'true', the database will use the external endpoint for OSS Cluster API. This setting blocks the database's private endpoint. Can only be set if 'supportOSSClusterAPI' is 'true'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// Optional. A public key client TLS/SSL certificate with new line characters replaced with '\n'. If specified, mTLS authentication will be required to authenticate user connections if it is not already required. If set to an empty string, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_ssl_certificate: Option<String>,

    /// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections. If set to an empty list, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Optional. When 'true', requires TLS authentication for all connections - mTLS with valid clientTlsCertificates, regular TLS when clientTlsCertificates is not provided. If enableTls is set to 'false' while mTLS is required, it will remove the mTLS requirement and erase previously provided clientTlsCertificates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_tls: Option<bool>,

    /// Optional. Type and rate of data persistence in all regions that don't set local 'dataPersistence'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_data_persistence: Option<String>,

    /// Optional. Changes the password used to access the database in all regions that don't set a local 'password'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_password: Option<String>,

    /// Optional. List of source IP addresses or subnet masks to allow in all regions that don't set local 'sourceIp' settings. If set, Redis clients will be able to connect to this database only from within the specified source IP addresses ranges. Example: ['192.168.10.0/32', '192.168.12.0/24']
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_source_ip: Option<Vec<String>>,

    /// Optional. Redis database alert settings in all regions that don't set local 'alerts'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Optional. A list of regions and local settings to update.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regions: Option<Vec<LocalRegionProperties>>,

    /// Optional. Data eviction policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_eviction_policy: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Database slowlog entry
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseSlowLogEntry {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagCreateRequest {
    /// Database tag key.
    pub key: String,

    /// Database tag value.
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Optional. Throughput measurement method.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseThroughputSpec {
    /// Throughput measurement method. Use 'operations-per-second' for all new databases.
    pub by: String,

    /// Throughput value in the selected measurement method.
    pub value: i64,
}

/// Optional. Changes Remote backup configuration details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseBackupConfig {
    /// Optional. Determine if backup should be active. Default: null
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active: Option<bool>,

    /// Required when active is 'true'. Defines the interval between backups. Format: 'every-x-hours', where x is one of 24, 12, 6, 4, 2, or 1. Example: "every-4-hours"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup_interval: Option<String>,

    /// Optional. Hour when the backup starts. Available only for "every-12-hours" and "every-24-hours" backup intervals. Specified as an hour in 24-hour UTC time. Example: "14:00" is 2 PM UTC.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_utc: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_backup_time_utc: Option<String>,

    /// Required when active is 'true'. Type of storage to host backup files. Can be "aws-s3", "google-blob-storage", "azure-blob-storage", or "ftp". See [Set up backup storage locations](https://redis.io/docs/latest/operate/rc/databases/back-up-data/#set-up-backup-storage-locations) to learn how to set up backup storage locations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup_storage_type: Option<String>,

    /// Required when active is 'true'. Path to the backup storage location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage_path: Option<String>,
}

/// Optional. Redis advanced capabilities (also known as modules) to be provisioned in the database. Use GET /database-modules to get a list of available advanced capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseModuleSpec {
    /// Redis advanced capability name. Use GET /database-modules for a list of available capabilities.
    pub name: String,

    /// Optional. Redis advanced capability parameters. Use GET /database-modules to get the available capabilities and their parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, Value>>,
}

/// Optional. Changes Replica Of (also known as Active-Passive) configuration details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplicaOfSpec {
    /// Optional. This database will be a replica of the specified Redis databases, provided as a list of objects with endpoint and certificate details.
    pub sync_sources: Vec<DatabaseSyncSourceSpec>,
}

/// Regex rule for custom hashing policy
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegexRule {
    /// The ordinal/order of this rule
    pub ordinal: i32,

    /// The regex pattern for this rule
    pub pattern: String,
}

/// Backup configuration status (response)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Backup {
    /// Whether remote backup is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_remote_backup: Option<bool>,

    /// Backup time in UTC
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_utc: Option<String>,

    /// Backup interval (e.g., "every-24-hours", "every-12-hours")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<String>,

    /// Backup destination path
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination: Option<String>,
}

/// Security configuration (response)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Security {
    /// Whether default Redis user is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_default_user: Option<bool>,

    /// Whether SSL client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ssl_client_authentication: Option<bool>,

    /// Whether TLS client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_client_authentication: Option<bool>,

    /// List of source IP addresses allowed to connect
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_ips: Option<Vec<String>>,

    /// Database password (masked in responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// Whether TLS is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_tls: Option<bool>,
}

/// Clustering configuration (response)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Clustering {
    /// Number of shards
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_of_shards: Option<i32>,

    /// Regex rules for custom hashing
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regex_rules: Option<Vec<RegexRule>>,

    /// Hashing policy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hashing_policy: Option<String>,
}

/// Active-Active (CRDB) database information
///
/// Represents an Active-Active database with global settings and per-region configurations.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActiveActiveDatabase {
    /// Database ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

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

    /// Database protocol
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,

    /// Database status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

    /// Redis version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version: Option<String>,

    /// Memory storage type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_storage: Option<String>,

    /// Whether this is an Active-Active database
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_active_redis: Option<bool>,

    /// Timestamp when database was activated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activated_on: Option<String>,

    /// Timestamp of last modification
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,

    /// Support for OSS Cluster API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub support_oss_cluster_api: Option<bool>,

    /// Use external endpoint for OSS Cluster API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// Whether replication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replication: Option<bool>,

    /// Data eviction policy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_eviction_policy: Option<String>,

    /// Security configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security: Option<Security>,

    /// Redis modules enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modules: Option<Vec<DatabaseModuleSpec>>,

    /// Global data persistence setting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_data_persistence: Option<String>,

    /// Global source IP allowlist
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_source_ip: Option<Vec<String>>,

    /// Global password
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_password: Option<String>,

    /// Global alert configurations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Global enable default user setting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_enable_default_user: Option<bool>,

    /// Per-region CRDB database configurations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crdb_databases: Option<Vec<CrdbDatabase>>,

    /// Whether automatic minor version upgrades are enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_minor_version_upgrade: Option<bool>,
}

/// Per-region configuration for an Active-Active (CRDB) database
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CrdbDatabase {
    /// Cloud provider
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,

    /// Cloud region
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    /// Redis version compliance
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version_compliance: Option<String>,

    /// Public endpoint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_endpoint: Option<String>,

    /// Private endpoint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_endpoint: Option<String>,

    /// Memory limit in GB
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_in_gb: Option<f64>,

    /// Dataset size in GB
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dataset_size_in_gb: Option<f64>,

    /// Memory used in MB
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_used_in_mb: Option<f64>,

    /// Read operations per second
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_operations_per_second: Option<i32>,

    /// Write operations per second
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_operations_per_second: Option<i32>,

    /// Data persistence setting for this region
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_persistence: Option<String>,

    /// Alert configurations for this region
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Security configuration for this region
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security: Option<Security>,

    /// Backup configuration for this region
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup: Option<Backup>,

    /// Query performance factor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_performance_factor: Option<String>,
}

/// Database backup request message
///
/// # Example
///
/// ```
/// use redis_cloud::flexible::databases::DatabaseBackupRequest;
///
/// let request = DatabaseBackupRequest::builder()
///     .region_name("us-east-1")
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseBackupRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub database_id: Option<i32>,

    /// Required for Active-Active databases. Name of the cloud provider region to back up. When backing up an Active-Active database, you must back up each region separately.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub region_name: Option<String>,

    /// Optional. Manually backs up data to this location, instead of the set 'remoteBackup' location.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub adhoc_backup_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,
}

/// Database
///
/// Represents a Redis Cloud database with all known API fields as first-class struct members.
/// The `extra` field is reserved only for truly unknown/future fields that may be added to the API.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Database {
    /// Database ID - always present in API responses
    pub database_id: i32,

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

    /// Database status (e.g., "active", "pending", "error", "draft")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

    /// Cloud provider (e.g., "AWS", "GCP", "Azure")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,

    /// Cloud region (e.g., "us-east-1", "europe-west1")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    /// Redis version (e.g., "7.2", "7.0")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version: Option<String>,

    /// Redis Serialization Protocol version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resp_version: Option<String>,

    /// Total memory limit in GB (including replication and overhead)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_in_gb: Option<f64>,

    /// Dataset size in GB (actual data size, excluding replication)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dataset_size_in_gb: Option<f64>,

    /// Memory used in MB
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_used_in_mb: Option<f64>,

    /// Private endpoint for database connections
    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_endpoint: Option<String>,

    /// Public endpoint for database connections (if enabled)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_endpoint: Option<String>,

    /// TCP port on which the database is available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<i32>,

    /// Data eviction policy (e.g., "volatile-lru", "allkeys-lru", "noeviction")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_eviction_policy: Option<String>,

    /// Data persistence setting (e.g., "aof-every-1-sec", "snapshot-every-1-hour", "none")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_persistence: Option<String>,

    /// Whether replication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replication: Option<bool>,

    /// Protocol used (e.g., "redis", "memcached")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,

    /// Support for OSS Cluster API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub support_oss_cluster_api: Option<bool>,

    /// Use external endpoint for OSS Cluster API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// Whether TLS is enabled for connections
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_tls: Option<bool>,

    /// Throughput measurement configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub throughput_measurement: Option<DatabaseThroughputSpec>,

    /// Local throughput measurement for Active-Active databases
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_throughput_measurement: Option<Vec<LocalThroughput>>,

    /// Average item size in bytes (for Auto Tiering)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub average_item_size_in_bytes: Option<i64>,

    /// Path to periodic backup storage location
    #[serde(skip_serializing_if = "Option::is_none")]
    pub periodic_backup_path: Option<String>,

    /// Remote backup configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_backup: Option<DatabaseBackupConfig>,

    /// List of source IP addresses or subnet masks allowed to connect
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_ip: Option<Vec<String>>,

    /// Client TLS/SSL certificate (deprecated, use `client_tls_certificates`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_ssl_certificate: Option<String>,

    /// List of client TLS/SSL certificates for mTLS authentication
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Database password (masked in responses for security)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// Memcached SASL username
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sasl_username: Option<String>,

    /// Memcached SASL password (masked in responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sasl_password: Option<String>,

    /// Database alert configurations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Redis modules/capabilities enabled on this database
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modules: Option<Vec<DatabaseModuleSpec>>,

    /// Database hashing policy for clustering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sharding_type: Option<String>,

    /// Query performance factor (for search and query databases)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_performance_factor: Option<String>,

    /// List of databases this database is a replica of
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replica_of: Option<Vec<String>>,

    /// Replica configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replica: Option<ReplicaOfSpec>,

    /// Whether default Redis user is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_default_user: Option<bool>,

    /// Whether this is an Active-Active (CRDB) database
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_active_redis: Option<bool>,

    /// Memory storage type: "ram" or "ram-and-flash" (Auto Tiering)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_storage: Option<String>,

    /// Redis version compliance status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version_compliance: Option<String>,

    /// Whether automatic minor version upgrades are enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_minor_version_upgrade: Option<bool>,

    /// Number of shards in the database cluster
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_of_shards: Option<i32>,

    /// Regex rules for custom hashing policy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regex_rules: Option<Vec<RegexRule>>,

    /// Whether SSL client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ssl_client_authentication: Option<bool>,

    /// Whether TLS client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_client_authentication: Option<bool>,

    /// Timestamp when database was activated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activated: Option<String>,

    /// Timestamp of last modification
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,

    /// HATEOAS links for API navigation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Optional. Changes Redis database alert details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseAlertSpec {
    /// Alert type. Available options depend on Plan type. See [Configure alerts](https://redis.io/docs/latest/operate/rc/databases/monitor-performance/#configure-metric-alerts) for more information.
    pub name: String,

    /// Value over which an alert will be sent. Default values and range depend on the alert type. See [Configure alerts](https://redis.io/docs/latest/operate/rc/databases/monitor-performance/#configure-metric-alerts) for more information.
    pub value: i32,
}

/// Request structure for creating a new Pro database
///
/// Contains all configuration options for creating a database in a Pro subscription,
/// including memory settings, replication, persistence, modules, and networking.
///
/// # Example
///
/// ```
/// use redis_cloud::flexible::databases::DatabaseCreateRequest;
///
/// let request = DatabaseCreateRequest::builder()
///     .name("my-database")
///     .memory_limit_in_gb(1.0)
///     .replication(true)
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseCreateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    /// Optional. When 'false': Creates a deployment plan and deploys it, creating any resources required by the plan. When 'true': creates a read-only deployment plan and does not create any resources. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dry_run: Option<bool>,

    /// Name of the database. Database name is limited to 40 characters or less and must include only letters, digits, and hyphens ('-'). It must start with a letter and end with a letter or digit.
    #[builder(setter(into))]
    pub name: String,

    /// Optional. Database protocol. Only set to 'memcached' if you have a legacy application. Default: 'redis'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub protocol: Option<String>,

    /// Optional. TCP port on which the database is available (10000-19999). Generated automatically if not set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub port: Option<i32>,

    /// Optional. Total memory in GB, including replication and other overhead. You cannot set both datasetSizeInGb and totalMemoryInGb.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub memory_limit_in_gb: Option<f64>,

    /// Optional. The maximum amount of data in the dataset for this database in GB. You cannot set both datasetSizeInGb and totalMemoryInGb. If 'replication' is 'true', the database's total memory will be twice as large as the datasetSizeInGb. If 'replication' is false, the database's total memory will be the datasetSizeInGb value.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dataset_size_in_gb: Option<f64>,

    /// Optional. If specified, redisVersion defines the Redis database version. If omitted, the Redis version will be set to the default version (available in 'GET /subscriptions/redis-versions')
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub redis_version: Option<String>,

    /// Optional. Redis Serialization Protocol version. Must be compatible with Redis version.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub resp_version: Option<String>,

    /// Optional. Support [OSS Cluster API](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#oss-cluster-api). Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub support_oss_cluster_api: Option<bool>,

    /// Optional. If set to 'true', the database will use the external endpoint for OSS Cluster API. This setting blocks the database's private endpoint. Can only be set if 'supportOSSClusterAPI' is 'true'. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// Optional. Type and rate of data persistence in persistent storage. Default: 'none'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_persistence: Option<String>,

    /// Optional. Data eviction policy. Default: 'volatile-lru'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_eviction_policy: Option<String>,

    /// Optional. Sets database replication. Default: 'true'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replication: Option<bool>,

    /// Optional. This database will be a replica of the specified Redis databases provided as one or more URI(s). Example: 'redis://user:password@host:port'. If the URI provided is a Redis Cloud database, only host and port should be provided. Example: ['<redis://endpoint1:6379>', '<redis://endpoint2:6380>'].
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica_of: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica: Option<ReplicaOfSpec>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub throughput_measurement: Option<DatabaseThroughputSpec>,

    /// Optional. Expected throughput per region for an Active-Active database. Default: 1000 read and write ops/sec for each region
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub local_throughput_measurement: Option<Vec<LocalThroughput>>,

    /// Optional. Relevant only to ram-and-flash (also known as Auto Tiering) subscriptions. Estimated average size in bytes of the items stored in the database. Default: 1000
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub average_item_size_in_bytes: Option<i64>,

    /// Optional. The path to a backup storage location. If specified, the database will back up every 24 hours to this location, and you can manually back up the database to this location at any time.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub periodic_backup_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub remote_backup: Option<DatabaseBackupConfig>,

    /// Optional. List of source IP addresses or subnet masks to allow. If specified, Redis clients will be able to connect to this database only from within the specified source IP addresses ranges. Example: '['192.168.10.0/32', '192.168.12.0/24']'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub source_ip: Option<Vec<String>>,

    /// Optional. A public key client TLS/SSL certificate with new line characters replaced with '\n'. If specified, mTLS authentication will be required to authenticate user connections. Default: 'null'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub client_ssl_certificate: Option<String>,

    /// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Optional. When 'true', requires TLS authentication for all connections - mTLS with valid clientTlsCertificates, regular TLS when clientTlsCertificates is not provided. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_tls: Option<bool>,

    /// Optional. Password to access the database. If not set, a random 32-character alphanumeric password will be automatically generated. Can only be set if 'protocol' is 'redis'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub password: Option<String>,

    /// Optional. Memcached (SASL) Username to access the database. If not set, the username will be set to a 'mc-' prefix followed by a random 5 character long alphanumeric. Can only be set if 'protocol' is 'memcached'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub sasl_username: Option<String>,

    /// Optional. Memcached (SASL) Password to access the database. If not set, a random 32 character long alphanumeric password will be automatically generated. Can only be set if 'protocol' is 'memcached'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub sasl_password: Option<String>,

    /// Optional. Redis database alert details.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Optional. Redis advanced capabilities (also known as modules) to be provisioned in the database. Use GET /database-modules to get a list of available advanced capabilities.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub modules: Option<Vec<DatabaseModuleSpec>>,

    /// Optional. Database [Hashing policy](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#manage-the-hashing-policy).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub sharding_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,

    /// Optional. The query performance factor adds extra compute power specifically for search and query databases. You can increase your queries per second by the selected factor.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub query_performance_factor: Option<String>,
}

/// Database import request
///
/// # Example
///
/// ```
/// use redis_cloud::flexible::databases::DatabaseImportRequest;
///
/// let request = DatabaseImportRequest::builder()
///     .source_type("aws-s3")
///     .import_from_uri(vec!["s3://bucket/backup.rdb".to_string()])
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseImportRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub database_id: Option<i32>,

    /// Type of storage from which to import the database RDB file or Redis data.
    #[builder(setter(into))]
    pub source_type: String,

    /// One or more paths to source data files or Redis databases, as appropriate to specified source type.
    pub import_from_uri: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,
}

/// Redis list of database tags
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudTags {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_id: Option<i32>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Upgrades the specified Pro database to a later Redis version.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseUpgradeRedisVersionRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    /// The target Redis version the database will be upgraded to. Use GET /subscriptions/redis-versions to get a list of available Redis versions.
    pub target_redis_version: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// `DatabaseSlowLogEntries`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseSlowLogEntries {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entries: Option<Vec<DatabaseSlowLogEntry>>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Optional. A list of regions and local settings to update.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalRegionProperties {
    /// Required. Name of the region to update.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_backup: Option<DatabaseBackupConfig>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_throughput_measurement: Option<LocalThroughput>,

    /// Optional. Type and rate of data persistence for this region. If set, 'globalDataPersistence' will not apply to this region.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_persistence: Option<String>,

    /// Optional. Changes the password used to access the database in this region. If set, 'globalPassword' will not apply to this region.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// Optional. List of source IP addresses or subnet masks to allow in this region. If set, Redis clients will be able to connect to the database in this region only from within the specified source IP addresses ranges, and 'globalSourceIp' will not apply to this region. Example: ['192.168.10.0/32', '192.168.12.0/24']
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_ip: Option<Vec<String>>,

    /// Optional. Redis database alert settings for this region. If set, 'glboalAlerts' will not apply to this region.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Optional. Redis Serialization Protocol version for this region. Must be compatible with Redis version.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resp_version: Option<String>,
}

/// `TaskStateUpdate`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStateUpdate {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

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

    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<ProcessorResponse>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Database update request
///
/// # Example
///
/// ```
/// use redis_cloud::flexible::databases::DatabaseUpdateRequest;
///
/// let request = DatabaseUpdateRequest::builder()
///     .name("updated-name")
///     .memory_limit_in_gb(2.0)
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub database_id: Option<i32>,

    /// Optional. When 'false': Creates a deployment plan and deploys it, updating any resources required by the plan. When 'true': creates a read-only deployment plan and does not update any resources. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dry_run: Option<bool>,

    /// Optional. Updated database name.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub name: Option<String>,

    /// Optional. Total memory in GB, including replication and other overhead. You cannot set both datasetSizeInGb and totalMemoryInGb.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub memory_limit_in_gb: Option<f64>,

    /// Optional. The maximum amount of data in the dataset for this database in GB. You cannot set both datasetSizeInGb and totalMemoryInGb. If 'replication' is 'true', the database's total memory will be twice as large as the datasetSizeInGb.If 'replication' is false, the database's total memory will be the datasetSizeInGb value.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dataset_size_in_gb: Option<f64>,

    /// Optional. Redis Serialization Protocol version. Must be compatible with Redis version.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub resp_version: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub throughput_measurement: Option<DatabaseThroughputSpec>,

    /// Optional. Type and rate of data persistence in persistent storage.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_persistence: Option<String>,

    /// Optional. Data eviction policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_eviction_policy: Option<String>,

    /// Optional. Turns database replication on or off.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replication: Option<bool>,

    /// Optional. Hashing policy Regex rules. Used only if 'shardingType' is 'custom-regex-rules'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub regex_rules: Option<Vec<String>>,

    /// Optional. This database will be a replica of the specified Redis databases provided as one or more URI(s). Example: 'redis://user:password@host:port'. If the URI provided is a Redis Cloud database, only host and port should be provided. Example: ['<redis://endpoint1:6379>', '<redis://endpoint2:6380>'].
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica_of: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica: Option<ReplicaOfSpec>,

    /// Optional. Support Redis [OSS Cluster API](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#oss-cluster-api).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub support_oss_cluster_api: Option<bool>,

    /// Optional. If set to 'true', the database will use the external endpoint for OSS Cluster API. This setting blocks the database's private endpoint. Can only be set if 'supportOSSClusterAPI' is 'true'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// Optional. Changes the password used to access the database with the 'default' user. Can only be set if 'protocol' is 'redis'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub password: Option<String>,

    /// Optional. Changes the Memcached (SASL) username to access the database. Can only be set if 'protocol' is 'memcached'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub sasl_username: Option<String>,

    /// Optional. Changes the Memcached (SASL) password to access the database. Can only be set if 'protocol' is 'memcached'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub sasl_password: Option<String>,

    /// Optional. List of source IP addresses or subnet masks to allow. If specified, Redis clients will be able to connect to this database only from within the specified source IP addresses ranges. Example: '['192.168.10.0/32', '192.168.12.0/24']'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub source_ip: Option<Vec<String>>,

    /// Optional. A public key client TLS/SSL certificate with new line characters replaced with '\n'. If specified, mTLS authentication will be required to authenticate user connections if it is not already required. If set to an empty string, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub client_ssl_certificate: Option<String>,

    /// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections. If set to an empty list, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Optional. When 'true', requires TLS authentication for all connections - mTLS with valid clientTlsCertificates, regular TLS when clientTlsCertificates is not provided. If enableTls is set to 'false' while mTLS is required, it will remove the mTLS requirement and erase previously provided clientTlsCertificates.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_tls: Option<bool>,

    /// Optional. When 'true', allows connecting to the database with the 'default' user. When 'false', only defined access control users can connect to the database. Can only be set if 'protocol' is 'redis'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_default_user: Option<bool>,

    /// Optional. Changes the backup location path. If specified, the database will back up every 24 hours to this location, and you can manually back up the database to this location at any time. If set to an empty string, the backup path will be removed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub periodic_backup_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub remote_backup: Option<DatabaseBackupConfig>,

    /// Optional. Changes Redis database alert details.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,

    /// Optional. Changes the query performance factor. The query performance factor adds extra compute power specifically for search and query databases. You can increase your queries per second by the selected factor.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub query_performance_factor: Option<String>,
}

// ============================================================================
// Handler
// ============================================================================

/// Handler for Pro database operations
///
/// Manages database lifecycle, configuration, backup/restore, import/export,
/// and monitoring for Redis Cloud Pro subscriptions.
pub struct DatabaseHandler {
    client: CloudClient,
}

impl DatabaseHandler {
    /// Create a new handler
    #[must_use]
    pub fn new(client: CloudClient) -> Self {
        Self { client }
    }

    /// Get all databases in a Pro subscription
    ///
    /// Gets a list of all databases in the specified Pro subscription.
    ///
    /// GET /subscriptions/{subscriptionId}/databases
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `offset` - Optional offset for pagination
    /// * `limit` - Optional limit for pagination
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// // Get all databases in subscription 123
    /// let databases = client.databases().get_subscription_databases(123, None, None).await?;
    ///
    /// // With pagination
    /// let page = client.databases().get_subscription_databases(123, Some(0), Some(10)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_subscription_databases(
        &self,
        subscription_id: i32,
        offset: Option<i32>,
        limit: Option<i32>,
    ) -> Result<AccountSubscriptionDatabases> {
        let mut query = Vec::new();
        if let Some(v) = offset {
            query.push(format!("offset={v}"));
        }
        if let Some(v) = limit {
            query.push(format!("limit={v}"));
        }
        let query_string = if query.is_empty() {
            String::new()
        } else {
            format!("?{}", query.join("&"))
        };
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases{query_string}"
            ))
            .await
    }

    /// Create Pro database in existing subscription
    /// Creates a new database in an existing Pro subscription.
    ///
    /// POST /subscriptions/{subscriptionId}/databases
    pub async fn create_database(
        &self,
        subscription_id: i32,
        request: &DatabaseCreateRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/subscriptions/{subscription_id}/databases"),
                request,
            )
            .await
    }

    /// Delete Pro database
    /// Deletes a database from a Pro subscription.
    ///
    /// DELETE /subscriptions/{subscriptionId}/databases/{databaseId}
    pub async fn delete_database_by_id(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        let response = self
            .client
            .delete_raw(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}"
            ))
            .await?;
        serde_json::from_value(response).map_err(Into::into)
    }

    /// Get a single Pro database
    ///
    /// Gets details and settings of a single database in a Pro subscription.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let database = client.databases().get_subscription_database_by_id(123, 456).await?;
    ///
    /// println!("Database: {} (status: {:?})",
    ///     database.name.unwrap_or_default(),
    ///     database.status);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_subscription_database_by_id(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<Database> {
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}"
            ))
            .await
    }

    /// Update Pro database
    /// Updates an existing Pro database.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}
    pub async fn update_database(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseUpdateRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .put(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}"),
                request,
            )
            .await
    }

    /// Get Pro database backup status
    /// Gets information on the latest backup attempt for this Pro database.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/backup
    pub async fn get_database_backup_status(
        &self,
        subscription_id: i32,
        database_id: i32,
        region_name: Option<String>,
    ) -> Result<TaskStateUpdate> {
        let mut query = Vec::new();
        if let Some(v) = region_name {
            query.push(format!("regionName={v}"));
        }
        let query_string = if query.is_empty() {
            String::new()
        } else {
            format!("?{}", query.join("&"))
        };
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/backup{query_string}"
            ))
            .await
    }

    /// Back up Pro database
    /// Manually back up the specified Pro database to a backup path. By default, backups will be stored in the 'remoteBackup' location for this database.
    ///
    /// POST /subscriptions/{subscriptionId}/databases/{databaseId}/backup
    pub async fn backup_database(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseBackupRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/backup"),
                request,
            )
            .await
    }

    /// Get Pro database TLS certificate
    /// Gets the X.509 PEM (base64) encoded server certificate for TLS connection to the database. Requires 'enableTLS' to be 'true' for the database.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/certificate
    pub async fn get_subscription_database_certificate(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<DatabaseCertificate> {
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/certificate"
            ))
            .await
    }

    /// Flush Pro database
    /// Deletes all data from the specified Pro database.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}/flush
    pub async fn flush_crdb(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &CrdbFlushRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .put(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/flush"),
                request,
            )
            .await
    }

    /// Get Pro database import status
    /// Gets information on the latest import attempt for this Pro database.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/import
    pub async fn get_database_import_status(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/import"
            ))
            .await
    }

    /// Import data to a Pro database
    /// Imports data from an RDB file or from a different Redis database into this Pro database. WARNING: Importing data into a database removes all existing data from the database.
    ///
    /// POST /subscriptions/{subscriptionId}/databases/{databaseId}/import
    pub async fn import_database(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseImportRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/import"),
                request,
            )
            .await
    }

    /// Update Active-Active database
    /// (Active-Active databases only) Updates database properties for an Active-Active database.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}/regions
    pub async fn update_crdb_local_properties(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &CrdbUpdatePropertiesRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .put(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/regions"),
                request,
            )
            .await
    }

    /// Get database slowlog
    /// Gets the slowlog for a specific database.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/slow-log
    pub async fn get_slow_log(
        &self,
        subscription_id: i32,
        database_id: i32,
        region_name: Option<String>,
    ) -> Result<DatabaseSlowLogEntries> {
        let mut query = Vec::new();
        if let Some(v) = region_name {
            query.push(format!("regionName={v}"));
        }
        let query_string = if query.is_empty() {
            String::new()
        } else {
            format!("?{}", query.join("&"))
        };
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/slow-log{query_string}"
            ))
            .await
    }

    /// Get database tags
    /// Gets a list of all database tags.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn get_tags(&self, subscription_id: i32, database_id: i32) -> Result<CloudTags> {
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/tags"
            ))
            .await
    }

    /// Add a database tag
    /// Adds a single database tag to a database.
    ///
    /// POST /subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn create_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseTagCreateRequest,
    ) -> Result<CloudTag> {
        self.client
            .post(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/tags"),
                request,
            )
            .await
    }

    /// Overwrite database tags
    /// Overwrites all tags on the database.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn update_tags(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseTagsUpdateRequest,
    ) -> Result<CloudTags> {
        self.client
            .put(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/tags"),
                request,
            )
            .await
    }

    /// Delete database tag
    /// Removes the specified tag from the database.
    ///
    /// DELETE /subscriptions/{subscriptionId}/databases/{databaseId}/tags/{tagKey}
    pub async fn delete_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        tag_key: String,
    ) -> Result<HashMap<String, Value>> {
        let response = self
            .client
            .delete_raw(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/tags/{tag_key}"
            ))
            .await?;
        serde_json::from_value(response).map_err(Into::into)
    }

    /// Update database tag value
    /// Updates the value of the specified database tag.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}/tags/{tagKey}
    pub async fn update_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        tag_key: String,
        request: &DatabaseTagUpdateRequest,
    ) -> Result<CloudTag> {
        self.client
            .put(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/tags/{tag_key}"),
                request,
            )
            .await
    }

    /// Get Pro database version upgrade status
    /// Gets information on the latest upgrade attempt for this Pro database.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/upgrade
    pub async fn get_database_redis_version_upgrade_status(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<BdbVersionUpgradeStatus> {
        self.client
            .get(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/upgrade"
            ))
            .await
    }

    /// Upgrade Pro database version
    ///
    /// POST /subscriptions/{subscriptionId}/databases/{databaseId}/upgrade
    pub async fn upgrade_database_redis_version(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseUpgradeRedisVersionRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/upgrade"),
                request,
            )
            .await
    }

    /// Get available target Redis versions for upgrade
    /// Gets a list of Redis versions that the database can be upgraded to.
    ///
    /// GET /subscriptions/{subscriptionId}/databases/{databaseId}/available-target-versions
    pub async fn get_available_target_versions(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<Value> {
        self.client
            .get_raw(&format!(
                "/subscriptions/{subscription_id}/databases/{database_id}/available-target-versions"
            ))
            .await
    }

    /// Flush Pro database (standard, non-Active-Active)
    /// Deletes all data from the specified Pro database.
    ///
    /// PUT /subscriptions/{subscriptionId}/databases/{databaseId}/flush
    pub async fn flush_database(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        // Empty body for standard flush
        self.client
            .put_raw(
                &format!("/subscriptions/{subscription_id}/databases/{database_id}/flush"),
                serde_json::json!({}),
            )
            .await
            .and_then(|v| serde_json::from_value(v).map_err(Into::into))
    }

    // ========================================================================
    // Pagination Helpers
    // ========================================================================

    /// Stream all databases in a Pro subscription
    ///
    /// Returns an async stream that automatically handles pagination, yielding
    /// individual [`Database`] items. This is useful when you need to process
    /// a large number of databases without loading them all into memory at once.
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    /// use futures::StreamExt;
    /// use std::pin::pin;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let handler = client.databases();
    /// let mut stream = pin!(handler.stream_databases(123));
    /// while let Some(result) = stream.next().await {
    ///     let database = result?;
    ///     println!("Database: {} (ID: {})", database.name.unwrap_or_default(), database.database_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn stream_databases(
        &self,
        subscription_id: i32,
    ) -> impl Stream<Item = Result<Database>> + '_ {
        self.stream_databases_with_page_size(subscription_id, 100)
    }

    /// Stream all databases with custom page size
    ///
    /// Like [`stream_databases`](Self::stream_databases), but allows specifying
    /// the page size for API requests.
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `page_size` - Number of databases to fetch per API request
    pub fn stream_databases_with_page_size(
        &self,
        subscription_id: i32,
        page_size: i32,
    ) -> impl Stream<Item = Result<Database>> + '_ {
        try_stream! {
            let mut offset = 0;

            loop {
                let response = self
                    .get_subscription_databases(subscription_id, Some(offset), Some(page_size))
                    .await?;

                // Extract databases from the response
                let databases = Self::extract_databases_from_response(&response);

                if databases.is_empty() {
                    break;
                }

                let count = databases.len();
                for db in databases {
                    yield db;
                }

                // If we got fewer than page_size, we've reached the end
                #[allow(clippy::cast_sign_loss)]
                if count < page_size as usize {
                    break;
                }

                offset += page_size;
            }
        }
    }

    /// Get all databases in a subscription (collected)
    ///
    /// Fetches all databases by automatically handling pagination and returns
    /// them as a single vector. Use [`stream_databases`](Self::stream_databases)
    /// if you prefer to process databases one at a time.
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let all_databases = client.databases().get_all_databases(123).await?;
    /// println!("Total databases: {}", all_databases.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_all_databases(&self, subscription_id: i32) -> Result<Vec<Database>> {
        let mut databases = Vec::new();
        let mut offset = 0;
        let page_size = 100;

        loop {
            let response = self
                .get_subscription_databases(subscription_id, Some(offset), Some(page_size))
                .await?;

            let page = Self::extract_databases_from_response(&response);
            let count = page.len();
            databases.extend(page);

            #[allow(clippy::cast_sign_loss)]
            if count < page_size as usize {
                break;
            }
            offset += page_size;
        }

        Ok(databases)
    }

    /// Extract databases from an `AccountSubscriptionDatabases` response
    fn extract_databases_from_response(response: &AccountSubscriptionDatabases) -> Vec<Database> {
        response
            .subscription
            .first()
            .map(|sub| sub.databases.clone())
            .unwrap_or_default()
    }

    // ========================================================================
    // Simplified API Methods
    // ========================================================================

    /// List databases in a subscription (simplified)
    ///
    /// Returns a flat list of databases, unwrapping the nested API response.
    /// This is a convenience method that wraps [`get_subscription_databases`](Self::get_subscription_databases).
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let databases = client.databases().list(123).await?;
    /// for db in databases {
    ///     println!("Database: {} (ID: {})", db.name.unwrap_or_default(), db.database_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list(&self, subscription_id: i32) -> Result<Vec<Database>> {
        let response = self
            .get_subscription_databases(subscription_id, None, None)
            .await?;
        Ok(Self::extract_databases_from_response(&response))
    }

    /// Get a database by ID (simplified)
    ///
    /// Alias for [`get_subscription_database_by_id`](Self::get_subscription_database_by_id).
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `database_id` - The database ID
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let database = client.databases().get(123, 456).await?;
    /// println!("Database: {} (status: {:?})", database.name.unwrap_or_default(), database.status);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get(&self, subscription_id: i32, database_id: i32) -> Result<Database> {
        self.get_subscription_database_by_id(subscription_id, database_id)
            .await
    }

    /// Create a database (simplified)
    ///
    /// Alias for [`create_database`](Self::create_database).
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `request` - The database creation request
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    /// use redis_cloud::flexible::databases::DatabaseCreateRequest;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let request = DatabaseCreateRequest::builder()
    ///     .name("my-database")
    ///     .memory_limit_in_gb(1.0)
    ///     .build();
    ///
    /// let task = client.databases().create(123, &request).await?;
    /// println!("Task ID: {:?}", task.task_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create(
        &self,
        subscription_id: i32,
        request: &DatabaseCreateRequest,
    ) -> Result<TaskStateUpdate> {
        self.create_database(subscription_id, request).await
    }

    /// Update a database (simplified)
    ///
    /// Alias for [`update_database`](Self::update_database).
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `database_id` - The database ID
    /// * `request` - The database update request
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    /// use redis_cloud::flexible::databases::DatabaseUpdateRequest;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let request = DatabaseUpdateRequest::builder()
    ///     .name("updated-name")
    ///     .build();
    ///
    /// let task = client.databases().update(123, 456, &request).await?;
    /// println!("Task ID: {:?}", task.task_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseUpdateRequest,
    ) -> Result<TaskStateUpdate> {
        self.update_database(subscription_id, database_id, request)
            .await
    }

    /// Delete a database (simplified)
    ///
    /// Alias for [`delete_database_by_id`](Self::delete_database_by_id).
    ///
    /// # Arguments
    ///
    /// * `subscription_id` - The subscription ID
    /// * `database_id` - The database ID
    ///
    /// # Example
    ///
    /// ```no_run
    /// use redis_cloud::CloudClient;
    ///
    /// # async fn example() -> redis_cloud::Result<()> {
    /// let client = CloudClient::builder()
    ///     .api_key("your-api-key")
    ///     .api_secret("your-api-secret")
    ///     .build()?;
    ///
    /// let task = client.databases().delete(123, 456).await?;
    /// println!("Task ID: {:?}", task.task_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete(&self, subscription_id: i32, database_id: i32) -> Result<TaskStateUpdate> {
        self.delete_database_by_id(subscription_id, database_id)
            .await
    }
}