leeca_proxmox 0.3.0

A modern, safe, and async-first SDK for interacting with Proxmox Virtual Environment servers
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
#![feature(error_generic_member_access)]

//! A safe and ergonomic Rust client for the Proxmox VE API.
//!
//! This crate provides a strongly-typed interface for interacting with Proxmox Virtual Environment.
//! Validation rules (like password strength, DNS resolution) are **opt-in** via a [`ValidationConfig`].
//! By default, only basic format checks are performed to ensure the values can be used in HTTP requests.
//!
//! # Example
//! ```no_run
//! use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
//!
//! #[tokio::main]
//! async fn main() -> ProxmoxResult<()> {
//!     let mut client = ProxmoxClient::builder()
//!         .host("192.168.1.182")
//!         .port(8006)
//!         .secure(false) // HTTP for local development
//!         .accept_invalid_certs(true) // Testing & Self signed certs
//!         .enable_password_strength(3) // Optional validation
//!         .block_reserved_usernames() // Optional validation
//!         .build()
//!         .await?;
//!
//!     client.login().await?;
//!     println!("Authenticated: {}", client.is_authenticated().await);
//!     Ok(())
//! }
//! ```

mod auth;
mod core;

pub use crate::core::domain::error::{ProxmoxError, ProxmoxResult, ValidationError};
pub use crate::core::domain::model::{
    cluster_resource::ClusterResource,
    node_dns::NodeDnsConfig,
    node_list_item::NodeListItem,
    node_status::{MemoryInfo, NodeStatus},
    vm::*,
};

use crate::{
    auth::application::service::login_service::LoginService,
    core::{
        domain::{
            model::{proxmox_auth::ProxmoxAuth, proxmox_connection::ProxmoxConnection},
            value_object::{
                ProxmoxCSRFToken, ProxmoxHost, ProxmoxPassword, ProxmoxPort, ProxmoxRealm,
                ProxmoxTicket, ProxmoxUrl, ProxmoxUsername, validate_host, validate_password,
                validate_port, validate_realm, validate_url, validate_username,
            },
        },
        infrastructure::api_client::ApiClient,
    },
};

use std::backtrace::Backtrace;
use std::io::Read;
use std::time::Duration;

/// Configuration for rate limiting.
#[derive(Debug, Clone, Copy)]
pub struct RateLimitConfig {
    /// Number of requests allowed per second (steady state).
    pub requests_per_second: u32,
    /// Maximum burst size (how many requests can be sent in a short burst).
    pub burst_size: u32,
}

/// Configuration for validating client inputs.
///
/// By default, all extra checks are disabled, meaning only basic format validation is performed.
/// You can enable specific checks by calling the corresponding builder methods.
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Minimum password strength (zxcvbn score 0-4). If `None`, password strength is not checked.
    pub password_min_score: Option<zxcvbn::Score>,
    /// If true, DNS resolution is performed for hostnames.
    pub resolve_dns: bool,
    /// If true, reserved usernames (root, admin, etc.) are rejected.
    pub block_reserved_usernames: bool,
    /// Ticket lifetime for expiration checks (default 2 hours).
    pub ticket_lifetime: Duration,
    /// CSRF token lifetime (default 5 minutes).
    pub csrf_lifetime: Duration,
    /// Optional rate limiting configuration. If `None`, no rate limiting is applied.
    pub rate_limit: Option<RateLimitConfig>,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            password_min_score: None,
            resolve_dns: false,
            block_reserved_usernames: false,
            ticket_lifetime: Duration::from_secs(7200),
            csrf_lifetime: Duration::from_secs(300),
            rate_limit: None, // default: no limiting
        }
    }
}

/// A strongly-typed client for the Proxmox VE API.
///
/// Use the builder to configure connection settings and validation rules.
#[derive(Debug)]
pub struct ProxmoxClient {
    api_client: ApiClient,
    config: ValidationConfig,
}

/// Builder for [`ProxmoxClient`].
#[derive(Debug)]
pub struct ProxmoxClientBuilder {
    host: Option<String>,
    port: Option<u16>,
    username: Option<String>,
    password: Option<String>,
    realm: Option<String>,
    secure: bool,
    accept_invalid_certs: bool,
    config: ValidationConfig,
    initial_auth: Option<ProxmoxAuth>,
}

impl Default for ProxmoxClientBuilder {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            username: None,
            password: None,
            realm: None,
            secure: true, // Default to HTTPS
            accept_invalid_certs: false,
            config: ValidationConfig::default(),
            initial_auth: None,
        }
    }
}

impl ProxmoxClientBuilder {
    /// Sets the Proxmox VE host address.
    #[must_use]
    pub fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    /// Sets the Proxmox VE API port (default 8006).
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Sets the authentication credentials.
    #[must_use]
    pub fn credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
        realm: impl Into<String>,
    ) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self.realm = Some(realm.into());
        self
    }

    /// Configures TLS security: `true` for HTTPS, `false` for HTTP.
    ///
    /// When `false`, certificate validation is also disabled for convenience.
    #[must_use]
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        if !secure {
            self.accept_invalid_certs = true;
        }
        self
    }

    /// Configures certificate validation: `true` accepts invalid/self-signed certificates.
    #[must_use]
    pub fn accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Replaces the validation configuration with a custom one.
    #[must_use]
    pub fn with_validation_config(mut self, config: ValidationConfig) -> Self {
        self.config = config;
        self
    }

    /// Enables password strength checking with a minimum score (0-4).
    #[must_use]
    pub fn enable_password_strength(mut self, min_score: u8) -> Self {
        self.config.password_min_score = Some(match min_score {
            0 => zxcvbn::Score::Zero,
            1 => zxcvbn::Score::One,
            2 => zxcvbn::Score::Two,
            3 => zxcvbn::Score::Three,
            4 => zxcvbn::Score::Four,
            _ => zxcvbn::Score::Three,
        });
        self
    }

    /// Enables DNS resolution for hostnames (may block during build).
    #[must_use]
    pub fn enable_dns_resolution(mut self) -> Self {
        self.config.resolve_dns = true;
        self
    }

    /// Blocks reserved usernames (root, admin, etc.).
    #[must_use]
    pub fn block_reserved_usernames(mut self) -> Self {
        self.config.block_reserved_usernames = true;
        self
    }

    /// Sets client‑side rate limiting: `requests_per_second` and `burst_size`.
    #[must_use]
    pub fn rate_limit(mut self, requests_per_second: u32, burst_size: u32) -> Self {
        self.config.rate_limit = Some(RateLimitConfig {
            requests_per_second,
            burst_size,
        });
        self
    }

    /// Load an authentication state from a reader and use it as the initial auth.
    /// The tokens will be validated for expiration. Returns an error if the data is malformed
    /// or if the tokens are already expired according to the client's validation config.
    pub async fn with_session<R: Read>(mut self, mut reader: R) -> ProxmoxResult<Self> {
        let mut data = String::new();
        reader.read_to_string(&mut data)?;
        let auth: ProxmoxAuth = serde_json::from_str(&data)?;
        // Validate expiration
        if let Some(csrf) = auth.csrf_token()
            && csrf.is_expired(self.config.csrf_lifetime)
        {
            return Err(ProxmoxError::Session(
                "Loaded CSRF token is expired".to_string(),
            ));
        }
        if auth.ticket().is_expired(self.config.ticket_lifetime) {
            return Err(ProxmoxError::Session(
                "Loaded ticket is expired".to_string(),
            ));
        }
        self.initial_auth = Some(auth);
        Ok(self)
    }

    /// Constructs a [`ProxmoxClient`] after validating all inputs according to the configuration.
    pub async fn build(self) -> ProxmoxResult<ProxmoxClient> {
        // Extract required fields
        let host_str = self.host.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "host".to_string(),
                message: "Host is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let port_num = self.port.unwrap_or(8006);
        let username_str = self.username.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "username".to_string(),
                message: "Username is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let password_str = self.password.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "password".to_string(),
                message: "Password is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let realm_str = self.realm.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "realm".to_string(),
                message: "Realm is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;

        // Perform validation
        validate_host(&host_str, self.config.resolve_dns).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_port(port_num).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;
        validate_username(&username_str, self.config.block_reserved_usernames).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_password(&password_str, self.config.password_min_score).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_realm(&realm_str).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;

        // Construct URL
        let scheme = if self.secure { "https" } else { "http" };
        let url_str = format!("{}://{}:{}/", scheme, host_str, port_num);
        validate_url(&url_str).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;

        // Create value objects (unchecked, already validated)
        let host = ProxmoxHost::new_unchecked(host_str);
        let port = ProxmoxPort::new_unchecked(port_num);
        let username = ProxmoxUsername::new_unchecked(username_str);
        let password = ProxmoxPassword::new_unchecked(password_str);
        let realm = ProxmoxRealm::new_unchecked(realm_str);
        let url = ProxmoxUrl::new_unchecked(url_str);

        let connection = ProxmoxConnection::new(
            host,
            port,
            username,
            password,
            realm,
            self.secure,
            self.accept_invalid_certs,
            url,
        );

        let api_client = ApiClient::new(connection, self.config.clone())?;
        if let Some(auth) = self.initial_auth {
            api_client.set_auth(auth).await;
        }

        Ok(ProxmoxClient {
            api_client,
            config: self.config,
        })
    }
}

impl ProxmoxClient {
    /// Creates a new builder with default settings.
    #[must_use]
    pub fn builder() -> ProxmoxClientBuilder {
        ProxmoxClientBuilder::default()
    }

    /// Authenticates with the Proxmox VE server.
    ///
    /// This method performs a login using the credentials provided during builder construction
    /// and stores the obtained ticket and CSRF token inside the client.
    pub async fn login(&mut self) -> ProxmoxResult<()> {
        let service = LoginService::new();
        let auth = service.execute(self.api_client.connection()).await?;
        self.api_client.set_auth(auth).await;
        Ok(())
    }

    /// Returns `true` if the client has a valid (non‑expired) authentication ticket.
    pub async fn is_authenticated(&self) -> bool {
        self.api_client.is_authenticated().await
    }

    /// Returns the authentication ticket, if any.
    pub async fn auth_token(&self) -> Option<ProxmoxTicket> {
        self.api_client.auth().await.map(|a| a.ticket().clone())
    }

    /// Returns the CSRF token, if any.
    pub async fn csrf_token(&self) -> Option<ProxmoxCSRFToken> {
        self.api_client
            .auth()
            .await
            .and_then(|a| a.csrf_token().cloned())
    }

    /// Checks if the stored ticket is expired according to the configured lifetime.
    pub async fn is_ticket_expired(&self) -> bool {
        if let Some(auth) = self.api_client.auth().await {
            auth.ticket().is_expired(self.config.ticket_lifetime)
        } else {
            true
        }
    }

    /// Checks if the stored CSRF token is expired according to the configured lifetime.
    pub async fn is_csrf_expired(&self) -> bool {
        if let Some(auth) = self.api_client.auth().await {
            auth.csrf_token()
                .map(|c| c.is_expired(self.config.csrf_lifetime))
                .unwrap_or(true)
        } else {
            true
        }
    }

    /// Serializes the current authentication state (if any) and saves it to a file.
    /// Returns the number of bytes written.
    pub async fn save_session_to_file<P: AsRef<std::path::Path>>(
        &self,
        path: P,
    ) -> ProxmoxResult<usize> {
        let auth = match self.api_client.auth().await {
            Some(auth) => auth,
            None => return Ok(0), // no auth to save
        };
        let json = serde_json::to_string(&auth)?;
        tokio::fs::write(path, &json).await?;
        Ok(json.len())
    }

    /// Loads an authentication state from a file and sets it as the current auth.
    /// Returns an error if the data is malformed or if the tokens are already expired
    /// (according to the client's validation config).
    pub async fn load_session_from_file<P: AsRef<std::path::Path>>(
        &mut self,
        path: P,
    ) -> ProxmoxResult<()> {
        let data = tokio::fs::read_to_string(path).await?;
        let auth: ProxmoxAuth = serde_json::from_str(&data)?;
        // Validate expiration
        if let Some(csrf) = auth.csrf_token()
            && csrf.is_expired(self.config.csrf_lifetime)
        {
            return Err(ProxmoxError::Session(
                "Loaded CSRF token is expired".to_string(),
            ));
        }
        if auth.ticket().is_expired(self.config.ticket_lifetime) {
            return Err(ProxmoxError::Session(
                "Loaded ticket is expired".to_string(),
            ));
        }
        self.api_client.set_auth(auth).await;
        Ok(())
    }

    /// Retrieves all resources in the cluster (VMs, containers, storage, nodes, etc.).
    ///
    /// This method calls the `/cluster/resources` endpoint and returns a list of
    /// [`ClusterResource`] enums. The list can be filtered by resource type, node,
    /// or status on the client side.
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails, the client is not authenticated,
    /// or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::ClusterResource;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("leeca", "password", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let resources = client.cluster_resources().await?;
    /// for resource in resources {
    ///     match resource {
    ///         ClusterResource::Qemu(vm) => println!("VM {} on node {}", vm.common.name.unwrap_or_default(), vm.common.node),
    ///         ClusterResource::Lxc(ct) => println!("Container {} on node {}", ct.common.name.unwrap_or_default(), ct.common.node),
    ///         _ => (),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn cluster_resources(&self) -> ProxmoxResult<Vec<ClusterResource>> {
        self.api_client.get("cluster/resources").await
    }

    /// Lists all nodes in the cluster.
    ///
    /// This method calls the `/nodes` endpoint and returns a list of nodes
    /// with their basic information and resource usage statistics.
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::NodeListItem;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("user", "pass", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let nodes = client.nodes().await?;
    /// for node in nodes {
    ///     println!("Node: {} (status: {})", node.node, node.status);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn nodes(&self) -> ProxmoxResult<Vec<NodeListItem>> {
        self.api_client.get("nodes").await
    }

    /// Retrieves detailed status information for a specific node.
    ///
    /// This method calls the `/nodes/{node}/status` endpoint and returns
    /// CPU, memory, swap, uptime, load average, and IO delay information.
    ///
    /// # Arguments
    /// * `node` - The name of the node (e.g., "pve1").
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails, the node doesn't exist,
    /// or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::NodeStatus;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("user", "pass", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let status = client.node_status("pve1").await?;
    /// println!("CPU: {:.2}%, IO Delay: {:.2}%", status.cpu * 100.0, status.wait.unwrap_or(0.0) * 100.0);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn node_status(&self, node: &str) -> ProxmoxResult<NodeStatus> {
        let path = format!("nodes/{}/status", node);
        self.api_client.get(&path).await
    }

    /// Retrieves DNS configuration for a specific node.
    ///
    /// This method calls the `/nodes/{node}/dns` endpoint and returns
    /// the DNS search domain and list of DNS servers.
    ///
    /// # Arguments
    /// * `node` - The name of the node (e.g., "pve1").
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::NodeDnsConfig;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("user", "pass", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let dns = client.node_dns("pve1").await?;
    /// println!("Search domain: {}", dns.domain);
    /// println!("DNS servers: {:?}", dns.servers);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn node_dns(&self, node: &str) -> ProxmoxResult<NodeDnsConfig> {
        let path = format!("nodes/{}/dns", node);
        self.api_client.get(&path).await
    }

    /// Lists all QEMU virtual machines on a specific node.
    ///
    /// # Arguments
    /// * `node` - The name of the node (e.g., "pve1").
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::VmListItem;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("user", "pass", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let vms = client.vms("pve1").await?;
    /// for vm in vms {
    ///     println!("VM {} (ID: {}): {}", vm.name, vm.vmid, vm.status);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn vms(&self, node: &str) -> ProxmoxResult<Vec<VmListItem>> {
        let path = format!("nodes/{}/qemu", node);
        self.api_client.get(&path).await
    }

    /// Retrieves detailed current status of a specific VM.
    ///
    /// # Arguments
    /// * `node` - The name of the node where the VM resides.
    /// * `vmid` - The VM identifier.
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails or the response cannot be parsed.
    ///
    /// # Example
    /// ```
    /// # use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
    /// # use leeca_proxmox::VmStatusCurrent;
    /// #
    /// # #[tokio::main]
    /// # async fn run() -> ProxmoxResult<()> {
    /// # let mut client = ProxmoxClient::builder()
    /// #     .host("example.com")
    /// #     .port(8006)
    /// #     .credentials("user", "pass", "pam")
    /// #     .build().await?;
    /// # client.login().await?;
    /// let status = client.vm_status("pve1", 100).await?;
    /// println!("VM {} is {}", status.name, status.status);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn vm_status(&self, node: &str, vmid: u32) -> ProxmoxResult<VmStatusCurrent> {
        let path = format!("nodes/{}/qemu/{}/status/current", node, vmid);
        self.api_client.get(&path).await
    }

    /// Starts a VM.
    ///
    /// Returns a task ID (UPID) that can be used to track the operation.
    ///
    /// # Arguments
    /// * `node` - The node where the VM resides.
    /// * `vmid` - The VM identifier.
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if the request fails.
    pub async fn start_vm(&self, node: &str, vmid: u32) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/status/start", node, vmid);
        self.api_client.post(&path, &serde_json::json!({})).await
    }

    /// Stops a VM immediately (like pulling the plug).
    ///
    /// Returns a task ID.
    pub async fn stop_vm(&self, node: &str, vmid: u32) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/status/stop", node, vmid);
        self.api_client.post(&path, &serde_json::json!({})).await
    }

    /// Shuts down a VM gracefully (ACPI signal).
    ///
    /// Returns a task ID.
    pub async fn shutdown_vm(&self, node: &str, vmid: u32) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/status/shutdown", node, vmid);
        self.api_client.post(&path, &serde_json::json!({})).await
    }

    /// Reboots a VM (like pressing reset button).
    ///
    /// Returns a task ID.
    pub async fn reboot_vm(&self, node: &str, vmid: u32) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/status/reboot", node, vmid);
        self.api_client.post(&path, &serde_json::json!({})).await
    }

    /// Hard resets a VM.
    ///
    /// Returns a task ID.
    pub async fn reset_vm(&self, node: &str, vmid: u32) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/status/reset", node, vmid);
        self.api_client.post(&path, &serde_json::json!({})).await
    }

    /// Deletes a VM.
    ///
    /// By default, this also removes associated disks. Use `purge: false` to keep disks.
    ///
    /// # Arguments
    /// * `node` - The node where the VM resides.
    /// * `vmid` - The VM identifier.
    /// * `purge` - If `true` (default), remove VM from configuration and all related data (disks, snapshots, backups). If `false`, only remove the configuration, keeping disks.
    ///
    /// Returns a task ID.
    pub async fn delete_vm(&self, node: &str, vmid: u32, purge: bool) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}", node, vmid);
        // For DELETE with query parameters, we need to construct URL with params.
        // Proxmox API accepts query parameters for DELETE requests.
        let url = if purge {
            format!("{}?purge=1", path)
        } else {
            format!("{}?purge=0", path)
        };
        self.api_client.delete(&url).await
    }

    /// Creates a new VM.
    ///
    /// # Arguments
    /// * `node` - The node where to create the VM.
    /// * `params` - Creation parameters (see [`CreateVmParams`]).
    ///
    /// Returns a task ID.
    ///
    /// # Errors
    /// Returns [`ProxmoxError`] if validation fails or the request cannot be sent.
    pub async fn create_vm(&self, node: &str, params: &CreateVmParams) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu", node);
        self.api_client.post(&path, params).await
    }

    /// Retrieves the full configuration of a VM.
    ///
    /// # Arguments
    /// * `node` - The node where the VM resides.
    /// * `vmid` - The VM identifier.
    ///
    /// Returns the current configuration.
    pub async fn vm_config(&self, node: &str, vmid: u32) -> ProxmoxResult<VmConfig> {
        let path = format!("nodes/{}/qemu/{}/config", node, vmid);
        self.api_client.get(&path).await
    }

    /// Updates the configuration of a VM.
    ///
    /// # Arguments
    /// * `node` - The node where the VM resides.
    /// * `vmid` - The VM identifier.
    /// * `params` - Parameters to update (fields with `Some` value will be updated, `None` leaves unchanged).
    ///
    /// Returns a task ID.
    ///
    /// # Note
    /// To delete a parameter, you need to set it to `null` or use a special value. The Proxmox API uses
    /// the `delete` query parameter for that. This is not yet supported; for now only setting values is possible.
    pub async fn update_vm_config(
        &self,
        node: &str,
        vmid: u32,
        params: &CreateVmParams, // Reusing CreateVmParams with Option fields works for updates
    ) -> ProxmoxResult<String> {
        let path = format!("nodes/{}/qemu/{}/config", node, vmid);
        self.api_client.put(&path, params).await
    }
}

#[cfg(test)]
mod tests {
    mod integration;
    mod resources;
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_builder_default_secure() {
        let builder = ProxmoxClientBuilder::default();
        assert!(builder.secure);
        assert!(!builder.accept_invalid_certs);
    }

    #[tokio::test]
    async fn test_builder_missing_host() {
        let builder = ProxmoxClientBuilder::default()
            .port(8006)
            .credentials("user", "pass", "pam");
        let err = builder.build().await.unwrap_err();
        assert!(
            matches!(err, ProxmoxError::Validation { source: ValidationError::Field { field, .. }, .. } if field == "host")
        );
    }

    #[tokio::test]
    async fn test_builder_missing_username() {
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006);
        let err = builder.build().await.unwrap_err();
        assert!(
            matches!(err, ProxmoxError::Validation { source: ValidationError::Field { field, .. }, .. } if field == "username")
        );
    }

    #[tokio::test]
    async fn test_builder_valid_minimal() {
        let client = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password123", "pam")
            .build()
            .await
            .unwrap();
        assert!(!client.is_authenticated().await);
        assert!(client.auth_token().await.is_none());
        assert!(client.csrf_token().await.is_none());
        // No ticket/CSRF => they are considered expired
        assert!(client.is_ticket_expired().await);
        assert!(client.is_csrf_expired().await);
    }

    #[tokio::test]
    async fn test_builder_with_validation_config() {
        let config = ValidationConfig {
            password_min_score: Some(zxcvbn::Score::Three),
            resolve_dns: true,
            block_reserved_usernames: true,
            ..Default::default()
        };
        // Use a password that meets length but is weak
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password", "pam") // length 8, weak
            .with_validation_config(config.clone());
        let err = builder.build().await.unwrap_err();
        assert!(matches!(
            err,
            ProxmoxError::Validation {
                source: ValidationError::ConstraintViolation(_),
                ..
            }
        ));

        // Now with strong password
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "Str0ng!P@ss", "pam")
            .with_validation_config(config);
        assert!(builder.build().await.is_ok());
    }

    #[tokio::test]
    async fn test_client_login_no_auth() {
        let client = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password123", "pam")
            .build()
            .await
            .unwrap();
        assert!(!client.is_authenticated().await);
    }

    #[tokio::test]
    async fn test_builder_enable_methods() {
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("root", "password", "pam") // length 8, weak password
            .enable_password_strength(3)
            .enable_dns_resolution()
            .block_reserved_usernames();
        // Should fail because password weak and username reserved
        let err = builder.build().await.unwrap_err();
        assert!(matches!(err, ProxmoxError::Validation { .. }));
    }

    #[test]
    fn test_validation_config_default() {
        let config = ValidationConfig::default();
        assert_eq!(config.password_min_score, None);
        assert!(!config.resolve_dns);
        assert!(!config.block_reserved_usernames);
        assert_eq!(config.ticket_lifetime, Duration::from_secs(7200));
        assert_eq!(config.csrf_lifetime, Duration::from_secs(300));
    }

    // Test expiration methods with mocked auth
    #[tokio::test]
    async fn test_expiration_checks() {
        use crate::core::domain::model::proxmox_auth::ProxmoxAuth;
        use crate::core::domain::value_object::{ProxmoxCSRFToken, ProxmoxTicket};

        let ticket = ProxmoxTicket::new_unchecked("PVE:ticket".to_string());
        let csrf = ProxmoxCSRFToken::new_unchecked("id:val".to_string());
        let auth = ProxmoxAuth::new(ticket, Some(csrf));

        // Build a client with a dummy connection (won't be used)
        let connection = ProxmoxConnection::new(
            ProxmoxHost::new_unchecked("host".to_string()),
            ProxmoxPort::new_unchecked(8006),
            ProxmoxUsername::new_unchecked("user".to_string()),
            ProxmoxPassword::new_unchecked("pass".to_string()),
            ProxmoxRealm::new_unchecked("pam".to_string()),
            true,
            false,
            ProxmoxUrl::new_unchecked("https://host:8006/".to_string()),
        );
        let api_client = ApiClient::new(connection, ValidationConfig::default()).unwrap();
        api_client.set_auth(auth).await;

        let client = ProxmoxClient {
            api_client,
            config: ValidationConfig::default(),
        };

        assert!(!client.is_ticket_expired().await);
        assert!(!client.is_csrf_expired().await);
    }

    #[tokio::test]
    async fn test_session_save_load() {
        use crate::core::domain::model::proxmox_auth::ProxmoxAuth;
        use crate::core::domain::value_object::{ProxmoxCSRFToken, ProxmoxTicket};
        use tempfile::NamedTempFile;

        let ticket = ProxmoxTicket::new_unchecked("PVE:ticket".to_string());
        let csrf = ProxmoxCSRFToken::new_unchecked("id:val".to_string());
        let auth = ProxmoxAuth::new(ticket.clone(), Some(csrf.clone()));

        // Build a client with dummy connection
        let connection = ProxmoxConnection::new(
            ProxmoxHost::new_unchecked("host".to_string()),
            ProxmoxPort::new_unchecked(8006),
            ProxmoxUsername::new_unchecked("user".to_string()),
            ProxmoxPassword::new_unchecked("pass".to_string()),
            ProxmoxRealm::new_unchecked("pam".to_string()),
            true,
            false,
            ProxmoxUrl::new_unchecked("https://host:8006/".to_string()),
        );
        let api_client = ApiClient::new(connection, ValidationConfig::default()).unwrap();
        api_client.set_auth(auth).await;

        let client = ProxmoxClient {
            api_client,
            config: ValidationConfig::default(),
        };

        // Save to temp file
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_path_buf();
        let written = client.save_session_to_file(&path).await.unwrap();
        assert!(written > 0);

        // Create a new client and load session
        let new_client_builder = ProxmoxClient::builder()
            .host("host")
            .port(8006)
            .credentials("user", "password", "pam")
            .secure(false)
            .accept_invalid_certs(false);
        let new_client = new_client_builder
            .with_session(std::fs::File::open(&path).unwrap())
            .await
            .unwrap()
            .build()
            .await
            .unwrap();

        assert!(new_client.is_authenticated().await);
        assert_eq!(
            client.auth_token().await.unwrap().as_str(),
            new_client.auth_token().await.unwrap().as_str()
        );
    }
}