appwrite 0.14.0-rc.1

Appwrite SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
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
//! Mongo service for Appwrite SDK

use crate::client::Client;

use reqwest::Method;
use serde_json::json;
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct Mongo {
    client: Client,
}

impl Mongo {
    pub fn new(client: &Client) -> Self {
        Self {
            client: client.clone(),
        }
    }

    pub fn client(&self) -> &Client {
        &self.client
    }

    /// List all dedicated databases. Results support pagination.
    pub async fn list(
        &self,
        queries: Option<Vec<String>>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseList> {
        let mut params = HashMap::new();
        if let Some(value) = queries {
            params.insert(
                "queries".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo".to_string();

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Create a new dedicated database with the chosen engine and configuration.
    /// Status will be 'provisioning' until the database is ready.
    #[allow(clippy::too_many_arguments)]
    pub async fn create(
        &self,
        database_id: impl Into<String>,
        name: impl Into<String>,
        version: Option<&str>,
        specification: Option<&str>,
        replicas: Option<i64>,
        sync_mode: Option<&str>,
        network_idle_timeout_seconds: Option<i64>,
        network_ip_allowlist: Option<Vec<String>>,
        idle_timeout_minutes: Option<i64>,
        pitr: Option<bool>,
        pitr_retention_days: Option<i64>,
        storage_autoscaling: Option<bool>,
        storage_autoscaling_threshold_percent: Option<i64>,
        storage_autoscaling_max_gb: Option<i64>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        params.insert("databaseId".to_string(), json!(database_id.into()));
        params.insert("name".to_string(), json!(name.into()));
        if let Some(value) = version {
            params.insert("version".to_string(), json!(value));
        }
        if let Some(value) = specification {
            params.insert("specification".to_string(), json!(value));
        }
        if let Some(value) = replicas {
            params.insert("replicas".to_string(), json!(value));
        }
        if let Some(value) = sync_mode {
            params.insert("syncMode".to_string(), json!(value));
        }
        if let Some(value) = network_idle_timeout_seconds {
            params.insert("networkIdleTimeoutSeconds".to_string(), json!(value));
        }
        if let Some(value) = network_ip_allowlist {
            params.insert(
                "networkIPAllowlist".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        if let Some(value) = idle_timeout_minutes {
            params.insert("idleTimeoutMinutes".to_string(), json!(value));
        }
        if let Some(value) = pitr {
            params.insert("pitr".to_string(), json!(value));
        }
        if let Some(value) = pitr_retention_days {
            params.insert("pitrRetentionDays".to_string(), json!(value));
        }
        if let Some(value) = storage_autoscaling {
            params.insert("storageAutoscaling".to_string(), json!(value));
        }
        if let Some(value) = storage_autoscaling_threshold_percent {
            params.insert(
                "storageAutoscalingThresholdPercent".to_string(),
                json!(value),
            );
        }
        if let Some(value) = storage_autoscaling_max_gb {
            params.insert("storageAutoscalingMaxGb".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo".to_string();

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// List the dedicated database specifications available on the current plan.
    /// Each specification reports its resource limits, pricing, and whether it is
    /// enabled for the organization.
    pub async fn list_specifications(
        &self,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseSpecificationList> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/specifications".to_string();

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get a dedicated database by its unique ID. Returns the database
    /// configuration and current status.
    pub async fn get(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Update a dedicated database configuration. All changes are applied with
    /// zero downtime. Specification changes (cpu, memory, storage) are handled via
    /// rolling cutover. Storage expansion is done online. All other settings are
    /// applied in-place.
    #[allow(clippy::too_many_arguments)]
    pub async fn update(
        &self,
        database_id: impl Into<String>,
        name: Option<&str>,
        status: Option<&str>,
        specification: Option<&str>,
        replicas: Option<i64>,
        sync_mode: Option<&str>,
        network_idle_timeout_seconds: Option<i64>,
        network_ip_allowlist: Option<Vec<String>>,
        idle_timeout_minutes: Option<i64>,
        pitr: Option<bool>,
        pitr_retention_days: Option<i64>,
        storage_autoscaling: Option<bool>,
        storage_autoscaling_threshold_percent: Option<i64>,
        storage_autoscaling_max_gb: Option<i64>,
        metrics_trace_sample_rate: Option<f64>,
        metrics_slow_query_log_threshold_ms: Option<i64>,
        sql_api_enabled: Option<bool>,
        sql_api_allowed_statements: Option<Vec<String>>,
        sql_api_max_rows: Option<i64>,
        sql_api_max_bytes: Option<i64>,
        sql_api_timeout_seconds: Option<i64>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        if let Some(value) = name {
            params.insert("name".to_string(), json!(value));
        }
        if let Some(value) = status {
            params.insert("status".to_string(), json!(value));
        }
        if let Some(value) = specification {
            params.insert("specification".to_string(), json!(value));
        }
        if let Some(value) = replicas {
            params.insert("replicas".to_string(), json!(value));
        }
        if let Some(value) = sync_mode {
            params.insert("syncMode".to_string(), json!(value));
        }
        if let Some(value) = network_idle_timeout_seconds {
            params.insert("networkIdleTimeoutSeconds".to_string(), json!(value));
        }
        if let Some(value) = network_ip_allowlist {
            params.insert(
                "networkIPAllowlist".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        if let Some(value) = idle_timeout_minutes {
            params.insert("idleTimeoutMinutes".to_string(), json!(value));
        }
        if let Some(value) = pitr {
            params.insert("pitr".to_string(), json!(value));
        }
        if let Some(value) = pitr_retention_days {
            params.insert("pitrRetentionDays".to_string(), json!(value));
        }
        if let Some(value) = storage_autoscaling {
            params.insert("storageAutoscaling".to_string(), json!(value));
        }
        if let Some(value) = storage_autoscaling_threshold_percent {
            params.insert(
                "storageAutoscalingThresholdPercent".to_string(),
                json!(value),
            );
        }
        if let Some(value) = storage_autoscaling_max_gb {
            params.insert("storageAutoscalingMaxGb".to_string(), json!(value));
        }
        if let Some(value) = metrics_trace_sample_rate {
            params.insert("metricsTraceSampleRate".to_string(), json!(value));
        }
        if let Some(value) = metrics_slow_query_log_threshold_ms {
            params.insert("metricsSlowQueryLogThresholdMs".to_string(), json!(value));
        }
        if let Some(value) = sql_api_enabled {
            params.insert("sqlApiEnabled".to_string(), json!(value));
        }
        if let Some(value) = sql_api_allowed_statements {
            params.insert(
                "sqlApiAllowedStatements".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        if let Some(value) = sql_api_max_rows {
            params.insert("sqlApiMaxRows".to_string(), json!(value));
        }
        if let Some(value) = sql_api_max_bytes {
            params.insert("sqlApiMaxBytes".to_string(), json!(value));
        }
        if let Some(value) = sql_api_timeout_seconds {
            params.insert("sqlApiTimeoutSeconds".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::PATCH, &path, Some(api_headers), Some(params))
            .await
    }

    /// Delete a dedicated database. This action is irreversible. The database
    /// status will be set to 'deleting' and all resources will be cleaned up.
    /// Deletion is allowed from any state, and repeating the call re-dispatches
    /// the cleanup.
    pub async fn delete(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<serde_json::Value> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::DELETE, &path, Some(api_headers), Some(params))
            .await
    }

    /// List all backups for a dedicated database. Results can be filtered by
    /// status and type.
    pub async fn list_backups(
        &self,
        database_id: impl Into<String>,
        queries: Option<Vec<String>>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseBackupList> {
        let mut params = HashMap::new();
        if let Some(value) = queries {
            params.insert(
                "queries".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Create a manual backup of a dedicated database. The backup will be created
    /// asynchronously and its status can be checked via the get backup endpoint.
    pub async fn create_backup(
        &self,
        database_id: impl Into<String>,
        r#type: Option<&str>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseBackup> {
        let mut params = HashMap::new();
        if let Some(value) = r#type {
            params.insert("type".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// List scheduled backup policies for a dedicated database.
    pub async fn list_backup_policies(
        &self,
        database_id: impl Into<String>,
        queries: Option<Vec<String>>,
    ) -> crate::error::Result<crate::models::BackupPolicyList> {
        let mut params = HashMap::new();
        if let Some(value) = queries {
            params.insert(
                "queries".to_string(),
                json!(value.into_iter().map(|s| s.into()).collect::<Vec<String>>()),
            );
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/policies"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Create a scheduled backup policy for a dedicated database.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_backup_policy(
        &self,
        database_id: impl Into<String>,
        policy_id: impl Into<String>,
        name: impl Into<String>,
        schedule: impl Into<String>,
        retention: i64,
        r#type: Option<&str>,
        enabled: Option<bool>,
    ) -> crate::error::Result<crate::models::BackupPolicy> {
        let mut params = HashMap::new();
        params.insert("policyId".to_string(), json!(policy_id.into()));
        params.insert("name".to_string(), json!(name.into()));
        params.insert("schedule".to_string(), json!(schedule.into()));
        params.insert("retention".to_string(), json!(retention));
        if let Some(value) = r#type {
            params.insert("type".to_string(), json!(value));
        }
        if let Some(value) = enabled {
            params.insert("enabled".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/policies"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get a scheduled backup policy for a dedicated database.
    pub async fn get_backup_policy(
        &self,
        database_id: impl Into<String>,
        policy_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::BackupPolicy> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/policies/{policyId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{policyId}", &policy_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Update a scheduled backup policy for a dedicated database.
    pub async fn update_backup_policy(
        &self,
        database_id: impl Into<String>,
        policy_id: impl Into<String>,
        name: Option<&str>,
        schedule: Option<&str>,
        retention: Option<i64>,
        enabled: Option<bool>,
    ) -> crate::error::Result<crate::models::BackupPolicy> {
        let mut params = HashMap::new();
        if let Some(value) = name {
            params.insert("name".to_string(), json!(value));
        }
        if let Some(value) = schedule {
            params.insert("schedule".to_string(), json!(value));
        }
        if let Some(value) = retention {
            params.insert("retention".to_string(), json!(value));
        }
        if let Some(value) = enabled {
            params.insert("enabled".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/policies/{policyId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{policyId}", &policy_id.into().to_string());

        self.client
            .call(Method::PATCH, &path, Some(api_headers), Some(params))
            .await
    }

    /// Delete a scheduled backup policy for a dedicated database. Backups already
    /// taken by the policy are kept until their retention expires.
    pub async fn delete_backup_policy(
        &self,
        database_id: impl Into<String>,
        policy_id: impl Into<String>,
    ) -> crate::error::Result<serde_json::Value> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/policies/{policyId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{policyId}", &policy_id.into().to_string());

        self.client
            .call(Method::DELETE, &path, Some(api_headers), Some(params))
            .await
    }

    /// Configure off-cluster backup storage for a dedicated database. Supports S3,
    /// GCS, and Azure Blob Storage destinations. Backups will be stored to the
    /// configured destination in addition to on-cluster storage.
    #[allow(clippy::too_many_arguments)]
    pub async fn update_backup_storage(
        &self,
        database_id: impl Into<String>,
        provider: impl Into<String>,
        bucket: impl Into<String>,
        access_key: impl Into<String>,
        secret_key: impl Into<String>,
        region: Option<&str>,
        prefix: Option<&str>,
        endpoint: Option<&str>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseBackupStorage> {
        let mut params = HashMap::new();
        params.insert("provider".to_string(), json!(provider.into()));
        params.insert("bucket".to_string(), json!(bucket.into()));
        if let Some(value) = region {
            params.insert("region".to_string(), json!(value));
        }
        if let Some(value) = prefix {
            params.insert("prefix".to_string(), json!(value));
        }
        if let Some(value) = endpoint {
            params.insert("endpoint".to_string(), json!(value));
        }
        params.insert("accessKey".to_string(), json!(access_key.into()));
        params.insert("secretKey".to_string(), json!(secret_key.into()));
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/storage"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::PUT, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get details of a specific database backup including its status, size, and
    /// timestamps.
    pub async fn get_backup(
        &self,
        database_id: impl Into<String>,
        backup_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseBackup> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/{backupId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{backupId}", &backup_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Delete a database backup. This will permanently remove the backup from
    /// storage and cannot be undone.
    pub async fn delete_backup(
        &self,
        database_id: impl Into<String>,
        backup_id: impl Into<String>,
    ) -> crate::error::Result<serde_json::Value> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/backups/{backupId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{backupId}", &backup_id.into().to_string());

        self.client
            .call(Method::DELETE, &path, Some(api_headers), Some(params))
            .await
    }

    /// List all ephemeral branches for a dedicated database. Returns branch
    /// metadata including ID, name, namespace, and expiration time.
    pub async fn list_branches(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseBranchList> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/branches"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Create an ephemeral database branch from the primary via PVC snapshot. The
    /// branch is a full copy of the database at the current point in time, useful
    /// for testing schema migrations or running experiments without affecting
    /// production data. Branches expire after the configured TTL (default 24
    /// hours). The branch is created asynchronously.
    pub async fn create_branch(
        &self,
        database_id: impl Into<String>,
        branch_id: Option<&str>,
        ttl: Option<i64>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        if let Some(value) = branch_id {
            params.insert("branchId".to_string(), json!(value));
        }
        if let Some(value) = ttl {
            params.insert("ttl".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/branches"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// Delete an ephemeral database branch. This removes the branch namespace, its
    /// PVC, and the associated VolumeSnapshot. The deletion runs asynchronously
    /// and is irreversible.
    pub async fn delete_branch(
        &self,
        database_id: impl Into<String>,
        branch_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/branches/{branchId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{branchId}", &branch_id.into().to_string());

        self.client
            .call(Method::DELETE, &path, Some(api_headers), Some(params))
            .await
    }

    /// Rotate the primary connection credentials for a dedicated database.
    /// Generates a new password and updates the database atomically. Previous
    /// credentials stop working immediately. Returns the database with a refreshed
    /// connection string carrying the new password.
    pub async fn update_credentials(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/credentials"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::PATCH, &path, Some(api_headers), Some(params))
            .await
    }

    /// Trigger a manual failover for a dedicated database with high availability
    /// enabled. Promotes a replica to primary. The failover runs asynchronously;
    /// poll the database document for status updates. A database left
    /// mid-operation also accepts this call as a repair once nothing is driving
    /// the operation it is stuck in. Repairing a failover that did not finish, a
    /// `failed` database, a stranded upgrade or migrate, or a stranded compute
    /// resize additionally requires `targetReplicaId` to name the member to
    /// promote, because the default target may be the member that operation
    /// already promoted.
    pub async fn create_failover(
        &self,
        database_id: impl Into<String>,
        target_replica_id: Option<&str>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        if let Some(value) = target_replica_id {
            params.insert("targetReplicaId".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/failovers"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// Update the maintenance window for a dedicated database. Maintenance
    /// operations like minor version upgrades will be performed during this
    /// window.
    pub async fn update_maintenance(
        &self,
        database_id: impl Into<String>,
        day: impl Into<String>,
        hour_utc: i64,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        params.insert("day".to_string(), json!(day.into()));
        params.insert("hourUtc".to_string(), json!(hour_utc));
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/maintenance"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::PATCH, &path, Some(api_headers), Some(params))
            .await
    }

    /// Migrate a database between shared and dedicated types. Shared to dedicated
    /// provisions an always-on dedicated instance; dedicated to shared converts to
    /// a serverless instance that scales to zero when idle. Data is copied to the
    /// target with a brief read-only window during cutover.
    pub async fn create_migration(
        &self,
        database_id: impl Into<String>,
        target_type: impl Into<String>,
        specification: Option<&str>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        params.insert("targetType".to_string(), json!(target_type.into()));
        if let Some(value) = specification {
            params.insert("specification".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/migrations"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// List the lifecycle operations recorded for a dedicated database, newest
    /// first. Every provision, update, restore, backup and replication action is
    /// recorded here with its outcome, including an attempt that was abandoned
    /// because another worker took over the database.
    pub async fn list_operations(
        &self,
        database_id: impl Into<String>,
        status: Option<&str>,
        limit: Option<i64>,
        offset: Option<i64>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseOperationList> {
        let mut params = HashMap::new();
        if let Some(value) = status {
            params.insert("status".to_string(), json!(value));
        }
        if let Some(value) = limit {
            params.insert("limit".to_string(), json!(value));
        }
        if let Some(value) = offset {
            params.insert("offset".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/operations"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get available point-in-time recovery windows for a dedicated database.
    /// Returns the earliest and latest recovery points.
    pub async fn get_pitr(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabasePITRWindows> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/pitr"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get high availability status for a dedicated database. Returns replica
    /// statuses, replication lag, and sync mode.
    pub async fn get_replicas(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseReplicas> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/replicas"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// List all restorations for a dedicated database. Results can be filtered by
    /// status and type.
    pub async fn list_restorations(
        &self,
        database_id: impl Into<String>,
        status: Option<&str>,
        r#type: Option<&str>,
        limit: Option<i64>,
        offset: Option<i64>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseRestorationList> {
        let mut params = HashMap::new();
        if let Some(value) = status {
            params.insert("status".to_string(), json!(value));
        }
        if let Some(value) = r#type {
            params.insert("type".to_string(), json!(value));
        }
        if let Some(value) = limit {
            params.insert("limit".to_string(), json!(value));
        }
        if let Some(value) = offset {
            params.insert("offset".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/restorations"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Restore a database from a backup or to a specific point in time (PITR). For
    /// backup restoration, provide a backupId. For PITR, provide a targetTime as
    /// an ISO 8601 datetime. PITR requires the database to have PITR enabled and
    /// is only available for enterprise databases.
    pub async fn create_restoration(
        &self,
        database_id: impl Into<String>,
        r#type: Option<&str>,
        backup_id: Option<&str>,
        target_database_id: Option<&str>,
        target_time: Option<&str>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseRestoration> {
        let mut params = HashMap::new();
        if let Some(value) = r#type {
            params.insert("type".to_string(), json!(value));
        }
        if let Some(value) = backup_id {
            params.insert("backupId".to_string(), json!(value));
        }
        if let Some(value) = target_database_id {
            params.insert("targetDatabaseId".to_string(), json!(value));
        }
        if let Some(value) = target_time {
            params.insert("targetTime".to_string(), json!(value));
        }
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/restorations"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get details of a specific database restoration including its status, type,
    /// and timestamps.
    pub async fn get_restoration(
        &self,
        database_id: impl Into<String>,
        restoration_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabaseRestoration> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/restorations/{restorationId}"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string())
            .replace("{restorationId}", &restoration_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Get real-time health and status information for a dedicated database.
    /// Returns health status, readiness, uptime, connection info, replica status,
    /// and volume information.
    pub async fn get_status(
        &self,
        database_id: impl Into<String>,
    ) -> crate::error::Result<crate::models::DatabaseStatus> {
        let params = HashMap::new();
        let mut api_headers = HashMap::new();
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/status"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::GET, &path, Some(api_headers), Some(params))
            .await
    }

    /// Upgrade a dedicated database to a new engine version. Uses blue-green
    /// deployment for zero-downtime cutover.
    pub async fn create_upgrade(
        &self,
        database_id: impl Into<String>,
        target_version: impl Into<String>,
    ) -> crate::error::Result<crate::models::DedicatedDatabase> {
        let mut params = HashMap::new();
        params.insert("targetVersion".to_string(), json!(target_version.into()));
        let mut api_headers = HashMap::new();
        api_headers.insert("content-type".to_string(), "application/json".to_string());
        api_headers.insert("accept".to_string(), "application/json".to_string());

        let path = "/mongo/{databaseId}/upgrades"
            .to_string()
            .replace("{databaseId}", &database_id.into().to_string());

        self.client
            .call(Method::POST, &path, Some(api_headers), Some(params))
            .await
    }
}

impl crate::services::Service for Mongo {
    fn client(&self) -> &Client {
        &self.client
    }
}

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

    #[test]
    fn test_mongo_creation() {
        let client = Client::new();
        let service = Mongo::new(&client);
        assert!(service.client().endpoint().contains("cloud.appwrite.io/v1"));
    }
}