manydns 1.1.1

Provider-agnostic DNS zone and record management, inspired by the Go libdns project
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
use std::error::Error;

use reqwest::{
    header::{HeaderMap, HeaderValue},
    Client as HttpClient,
};
use serde::{Deserialize, Serialize};

use crate::HttpClientConfig;

const DNSPOD_API_URL: &str = "https://api.dnspod.com";

/// Helper module for deserializing fields that can be either strings or integers.
/// DNSPod API inconsistently returns some IDs as strings and others as integers.
mod string_or_int {
    use serde::{self, Deserialize, Deserializer};

    pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum StringOrInt {
            String(String),
            Int(i64),
        }

        match StringOrInt::deserialize(deserializer)? {
            StringOrInt::String(s) => Ok(s),
            StringOrInt::Int(i) => Ok(i.to_string()),
        }
    }

    pub fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum StringOrInt {
            String(String),
            Int(i64),
            Null,
        }

        match StringOrInt::deserialize(deserializer)? {
            StringOrInt::String(s) => Ok(Some(s)),
            StringOrInt::Int(i) => Ok(Some(i.to_string())),
            StringOrInt::Null => Ok(None),
        }
    }
}

/// URL-encodes a string for use in application/x-www-form-urlencoded bodies.
/// This is necessary for values containing special characters like colons in IPv6 addresses.
fn url_encode(s: &str) -> String {
    let mut encoded = String::with_capacity(s.len() * 3);
    for byte in s.bytes() {
        match byte {
            // Unreserved characters (RFC 3986)
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                encoded.push(byte as char);
            }
            // Everything else gets percent-encoded
            _ => {
                encoded.push('%');
                encoded.push_str(&format!("{:02X}", byte));
            }
        }
    }
    encoded
}

/// Configuration for the DNSPod API client.
///
/// DNSPod requires a properly formatted User-Agent header that identifies
/// your application and provides contact information. This is mandatory
/// per the [API Development Specifications](https://docs.dnspod.com/api/api-development/).
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// The name of your program/application (not the library name).
    /// Example: "My DDNS Client"
    pub program_name: String,
    /// The version of your program/application.
    /// Example: "1.0.0"
    pub version: String,
    /// Contact email for Tencent to reach the API developer.
    /// Example: "developer@example.com"
    pub contact_email: String,
}

impl ClientConfig {
    /// Creates a new client configuration.
    ///
    /// # Arguments
    ///
    /// * `program_name` - The name of your program (not the library)
    /// * `version` - Your program's version
    /// * `contact_email` - Contact email for Tencent to reach you
    pub fn new(
        program_name: impl Into<String>,
        version: impl Into<String>,
        contact_email: impl Into<String>,
    ) -> Self {
        Self {
            program_name: program_name.into(),
            version: version.into(),
            contact_email: contact_email.into(),
        }
    }

    /// Builds the User-Agent string per DNSPod API requirements.
    ///
    /// Format: `ProgramName/Version (contact@email.com)`
    pub fn user_agent(&self) -> String {
        format!(
            "{}/{} ({})",
            self.program_name, self.version, self.contact_email
        )
    }
}

#[derive(Debug, Clone)]
pub struct Client {
    http_client: HttpClient,
    login_token: String,
}

impl Client {
    /// Creates a new DNSPod API client.
    ///
    /// # Arguments
    ///
    /// * `login_token` - The DNSPod API token in format `{TokenID},{Token}`.
    ///   Generate tokens at: <https://console.dnspod.com/account/token>
    ///   Note: These are DNSPod tokens, NOT Tencent Cloud API keys.
    /// * `config` - Client configuration including User-Agent details
    ///
    /// # User-Agent Requirement
    ///
    /// DNSPod API requires a properly formatted User-Agent header that identifies
    /// your application (not this library) and provides your contact email.
    /// The format is: `ProgramName/Version (contact@email.com)`
    ///
    /// See: <https://docs.dnspod.com/api/api-development/>
    pub fn new(login_token: &str, config: &ClientConfig) -> Result<Self, Box<dyn Error>> {
        Self::with_http_config(login_token, config, HttpClientConfig::default())
    }

    /// Creates a new DNSPod API client with custom HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `login_token` - The DNSPod API token
    /// * `config` - Client configuration including User-Agent details
    /// * `http_config` - HTTP client configuration for network binding
    pub fn with_http_config(
        login_token: &str,
        config: &ClientConfig,
        http_config: HttpClientConfig,
    ) -> Result<Self, Box<dyn Error>> {
        let user_agent = config.user_agent();
        let mut headers = HeaderMap::new();
        headers.insert(
            "Content-Type",
            HeaderValue::from_static("application/x-www-form-urlencoded"),
        );
        // UserAgent is required by DNSPod API - must identify the program (not library)
        // and include developer contact email
        headers.insert(
            "User-Agent",
            HeaderValue::from_str(&user_agent).map_err(|e| Box::new(e) as Box<dyn Error>)?,
        );

        let mut builder = HttpClient::builder().default_headers(headers);

        if let Some(timeout) = http_config.timeout {
            builder = builder.timeout(timeout);
        }

        if let Some(addr) = http_config.local_address {
            builder = builder.local_address(addr);
        }

        #[cfg(any(
            target_os = "android",
            target_os = "fuchsia",
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "tvos",
            target_os = "watchos",
            target_os = "illumos",
            target_os = "solaris",
        ))]
        if let Some(ref iface) = http_config.interface {
            builder = builder.interface(iface);
        }

        let http_client = builder.build()?;
        Ok(Self {
            http_client,
            login_token: login_token.to_string(),
        })
    }

    fn build_form_params(&self, params: &[(&str, &str)]) -> String {
        let mut form = format!("login_token={}&format=json", self.login_token);
        for (key, value) in params {
            form.push_str(&format!("&{}={}", key, url_encode(value)));
        }
        form
    }

    // Domain APIs

    pub async fn list_domains(
        &self,
        offset: Option<u32>,
        length: Option<u32>,
    ) -> Result<DomainListResponse, DnspodError> {
        let mut params = Vec::new();
        let offset_str;
        let length_str;

        if let Some(o) = offset {
            offset_str = o.to_string();
            params.push(("offset", offset_str.as_str()));
        }
        if let Some(l) = length {
            length_str = l.to_string();
            params.push(("length", length_str.as_str()));
        }

        let response = self
            .http_client
            .post(format!("{}/Domain.List", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: DomainListResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    pub async fn get_domain(&self, domain_id: &str) -> Result<DomainInfoResponse, DnspodError> {
        let params = [("domain_id", domain_id)];

        let response = self
            .http_client
            .post(format!("{}/Domain.Info", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: DomainInfoResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        // Ensure domain is present on success
        if result.domain.is_none() {
            return Err(DnspodError::Api(Status {
                code: "0".to_string(),
                message: "API returned success but no domain data".to_string(),
                created_at: None,
            }));
        }

        Ok(result)
    }

    pub async fn get_domain_by_name(
        &self,
        domain: &str,
    ) -> Result<DomainInfoResponse, DnspodError> {
        let params = [("domain", domain)];

        let response = self
            .http_client
            .post(format!("{}/Domain.Info", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: DomainInfoResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        // Ensure domain is present on success
        if result.domain.is_none() {
            return Err(DnspodError::Api(Status {
                code: "0".to_string(),
                message: "API returned success but no domain data".to_string(),
                created_at: None,
            }));
        }

        Ok(result)
    }

    pub async fn create_domain(&self, domain: &str) -> Result<DomainCreateResponse, DnspodError> {
        let params = [("domain", domain)];

        let response = self
            .http_client
            .post(format!("{}/Domain.Create", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: DomainCreateResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    pub async fn delete_domain(&self, domain_id: &str) -> Result<StatusResponse, DnspodError> {
        let params = [("domain_id", domain_id)];

        let response = self
            .http_client
            .post(format!("{}/Domain.Remove", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: StatusResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    // Record APIs

    pub async fn list_records(
        &self,
        domain_id: &str,
        offset: Option<u32>,
        length: Option<u32>,
    ) -> Result<RecordListResponse, DnspodError> {
        let mut params = vec![("domain_id", domain_id.to_string())];

        if let Some(o) = offset {
            params.push(("offset", o.to_string()));
        }
        if let Some(l) = length {
            params.push(("length", l.to_string()));
        }

        let form = params.iter().fold(
            format!("login_token={}&format=json", self.login_token),
            |acc, (k, v)| format!("{}&{}={}", acc, k, v),
        );

        let response = self
            .http_client
            .post(format!("{}/Record.List", DNSPOD_API_URL))
            .body(form)
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: RecordListResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            // Empty result is code 10, which is not an error for listing
            if result.status.code == "10" {
                return Ok(RecordListResponse {
                    status: result.status,
                    domain: result.domain,
                    info: result.info,
                    records: Some(Vec::new()),
                });
            }
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    pub async fn get_record(
        &self,
        domain_id: &str,
        record_id: &str,
    ) -> Result<RecordInfoResponse, DnspodError> {
        let params = [("domain_id", domain_id), ("record_id", record_id)];

        let response = self
            .http_client
            .post(format!("{}/Record.Info", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: RecordInfoResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn create_record(
        &self,
        domain_id: &str,
        sub_domain: &str,
        record_type: &str,
        record_line: &str,
        value: &str,
        mx: Option<u16>,
        ttl: Option<u64>,
    ) -> Result<RecordCreateResponse, DnspodError> {
        let mut params = vec![
            ("domain_id", domain_id.to_string()),
            ("sub_domain", sub_domain.to_string()),
            ("record_type", record_type.to_string()),
            ("record_line", record_line.to_string()),
            ("value", value.to_string()),
        ];

        if let Some(mx_val) = mx {
            params.push(("mx", mx_val.to_string()));
        }
        if let Some(ttl_val) = ttl {
            params.push(("ttl", ttl_val.to_string()));
        }

        let form = params.iter().fold(
            format!("login_token={}&format=json", self.login_token),
            |acc, (k, v)| format!("{}&{}={}", acc, k, url_encode(v)),
        );

        let response = self
            .http_client
            .post(format!("{}/Record.Create", DNSPOD_API_URL))
            .body(form)
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: RecordCreateResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn modify_record(
        &self,
        domain_id: &str,
        record_id: &str,
        sub_domain: &str,
        record_type: &str,
        record_line: &str,
        value: &str,
        mx: Option<u16>,
        ttl: Option<u64>,
    ) -> Result<RecordModifyResponse, DnspodError> {
        let mut params = vec![
            ("domain_id", domain_id.to_string()),
            ("record_id", record_id.to_string()),
            ("sub_domain", sub_domain.to_string()),
            ("record_type", record_type.to_string()),
            ("record_line", record_line.to_string()),
            ("value", value.to_string()),
        ];

        if let Some(mx_val) = mx {
            params.push(("mx", mx_val.to_string()));
        }
        if let Some(ttl_val) = ttl {
            params.push(("ttl", ttl_val.to_string()));
        }

        let form = params.iter().fold(
            format!("login_token={}&format=json", self.login_token),
            |acc, (k, v)| format!("{}&{}={}", acc, k, url_encode(v)),
        );

        let response = self
            .http_client
            .post(format!("{}/Record.Modify", DNSPOD_API_URL))
            .body(form)
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: RecordModifyResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    pub async fn delete_record(
        &self,
        domain_id: &str,
        record_id: &str,
    ) -> Result<StatusResponse, DnspodError> {
        let params = [("domain_id", domain_id), ("record_id", record_id)];

        let response = self
            .http_client
            .post(format!("{}/Record.Remove", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: StatusResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }

    pub async fn set_record_status(
        &self,
        domain_id: &str,
        record_id: &str,
        status: &str,
    ) -> Result<RecordStatusResponse, DnspodError> {
        let params = [
            ("domain_id", domain_id),
            ("record_id", record_id),
            ("status", status),
        ];

        let response = self
            .http_client
            .post(format!("{}/Record.Status", DNSPOD_API_URL))
            .body(self.build_form_params(&params))
            .send()
            .await
            .map_err(DnspodError::Request)?;

        let result: RecordStatusResponse = response.json().await.map_err(DnspodError::Request)?;

        if result.status.code != "1" {
            return Err(DnspodError::Api(result.status));
        }

        Ok(result)
    }
}

// Error types

#[derive(Debug)]
pub enum DnspodError {
    Request(reqwest::Error),
    Api(Status),
}

impl std::fmt::Display for DnspodError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DnspodError::Request(e) => write!(f, "Request error: {}", e),
            DnspodError::Api(status) => {
                write!(f, "API error {}: {}", status.code, status.message)
            }
        }
    }
}

impl std::error::Error for DnspodError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DnspodError::Request(e) => Some(e),
            DnspodError::Api(_) => None,
        }
    }
}

// Response types

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Status {
    pub code: String,
    pub message: String,
    pub created_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct StatusResponse {
    pub status: Status,
}

// Domain types

#[derive(Debug, Clone, Deserialize)]
pub struct Domain {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub punycode: Option<String>,
    #[serde(default)]
    pub grade: Option<String>,
    #[serde(default)]
    pub grade_title: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub ext_status: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub records: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub group_id: Option<String>,
    #[serde(default)]
    pub is_mark: Option<String>,
    #[serde(default)]
    pub remark: Option<String>,
    #[serde(default)]
    pub is_vip: Option<String>,
    #[serde(default)]
    pub searchengine_push: Option<String>,
    #[serde(default)]
    pub beian: Option<String>,
    #[serde(default)]
    pub created_on: Option<String>,
    #[serde(default)]
    pub updated_on: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub ttl: Option<String>,
    #[serde(default)]
    pub owner: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub user_id: Option<String>,
}

impl Domain {
    pub fn get_ttl(&self) -> u64 {
        self.ttl
            .as_ref()
            .and_then(|t| t.parse().ok())
            .unwrap_or(600)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct DomainListInfo {
    pub domain_total: Option<u32>,
    pub all_total: Option<u32>,
    pub mine_total: Option<u32>,
    pub share_total: Option<u32>,
    pub vip_total: Option<u32>,
    pub ismark_total: Option<u32>,
    pub pause_total: Option<u32>,
    pub error_total: Option<u32>,
    pub lock_total: Option<u32>,
    pub spam_total: Option<u32>,
    pub vip_expire: Option<u32>,
    pub share_out_total: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DomainListResponse {
    pub status: Status,
    #[serde(default)]
    pub info: Option<DomainListInfo>,
    #[serde(default)]
    pub domains: Option<Vec<Domain>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DomainInfoResponse {
    pub status: Status,
    /// Domain info - only present on successful responses
    #[serde(default)]
    pub domain: Option<Domain>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DomainCreateDomain {
    pub id: String,
    #[serde(default)]
    pub punycode: Option<String>,
    #[serde(default)]
    pub domain: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DomainCreateResponse {
    pub status: Status,
    pub domain: DomainCreateDomain,
}

// Record types

#[derive(Debug, Clone, Deserialize)]
pub struct Record {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub line: Option<String>,
    #[serde(rename = "type", default)]
    pub record_type: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub ttl: Option<String>,
    pub value: String,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub mx: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub enabled: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub monitor_status: Option<String>,
    #[serde(default)]
    pub remark: Option<String>,
    #[serde(default)]
    pub updated_on: Option<String>,
    #[serde(default)]
    pub hold: Option<String>,
}

impl Record {
    pub fn get_ttl(&self, default_ttl: u64) -> u64 {
        self.ttl
            .as_ref()
            .and_then(|t| t.parse().ok())
            .unwrap_or(default_ttl)
    }

    pub fn get_type(&self) -> &str {
        self.record_type.as_deref().unwrap_or("A")
    }
}

/// A DNSPod record with its associated default TTL for conversion.
///
/// This wrapper is used to implement `From` for converting DNSPod
/// [`Record`] types to generic [`crate::Record`] types, since the
/// default TTL is needed when the record doesn't specify one.
pub struct RecordWithTtl<'a> {
    /// The DNSPod record.
    pub record: &'a Record,
    /// The default TTL from the domain.
    pub default_ttl: u64,
}

impl<'a> RecordWithTtl<'a> {
    /// Creates a new record-with-TTL wrapper.
    pub fn new(record: &'a Record, default_ttl: u64) -> Self {
        Self {
            record,
            default_ttl,
        }
    }
}

impl From<RecordWithTtl<'_>> for crate::Record {
    fn from(value: RecordWithTtl<'_>) -> Self {
        let record = value.record;
        let typ = record.get_type().to_owned();
        let ttl = record.get_ttl(value.default_ttl);
        let data = crate::RecordData::from_raw(&typ, &record.value);

        crate::Record {
            id: record.id.clone(),
            host: record.name.clone(),
            data,
            ttl,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordInfo {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub sub_domain: String,
    pub record_type: String,
    pub record_line: String,
    pub value: String,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub mx: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub ttl: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub enabled: Option<String>,
    #[serde(default)]
    pub monitor_status: Option<String>,
    #[serde(default)]
    pub remark: Option<String>,
    #[serde(default)]
    pub updated_on: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub domain_id: Option<String>,
}

impl RecordInfo {
    pub fn get_ttl(&self, default_ttl: u64) -> u64 {
        self.ttl
            .as_ref()
            .and_then(|t| t.parse().ok())
            .unwrap_or(default_ttl)
    }
}

/// A DNSPod record info with its associated default TTL for conversion.
///
/// This wrapper is used to implement `From` for converting DNSPod
/// [`RecordInfo`] types to generic [`crate::Record`] types, since the
/// default TTL is needed when the record doesn't specify one.
pub struct RecordInfoWithTtl<'a> {
    /// The DNSPod record info.
    pub record: &'a RecordInfo,
    /// The default TTL from the domain.
    pub default_ttl: u64,
}

impl<'a> RecordInfoWithTtl<'a> {
    /// Creates a new record-info-with-TTL wrapper.
    pub fn new(record: &'a RecordInfo, default_ttl: u64) -> Self {
        Self {
            record,
            default_ttl,
        }
    }
}

impl From<RecordInfoWithTtl<'_>> for crate::Record {
    fn from(value: RecordInfoWithTtl<'_>) -> Self {
        let record = value.record;
        let ttl = record.get_ttl(value.default_ttl);

        crate::Record {
            id: record.id.clone(),
            host: record.sub_domain.clone(),
            data: crate::RecordData::from_raw(&record.record_type, &record.value),
            ttl,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordListInfo {
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub sub_domains: Option<String>,
    #[serde(default, deserialize_with = "string_or_int::deserialize_option")]
    pub record_total: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordListDomain {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub punycode: Option<String>,
    #[serde(default)]
    pub grade: Option<String>,
    #[serde(default)]
    pub owner: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordListResponse {
    pub status: Status,
    #[serde(default)]
    pub domain: Option<RecordListDomain>,
    #[serde(default)]
    pub info: Option<RecordListInfo>,
    #[serde(default)]
    pub records: Option<Vec<Record>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordInfoDomain {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub domain: String,
    #[serde(default)]
    pub domain_grade: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordInfoResponse {
    pub status: Status,
    pub domain: RecordInfoDomain,
    pub record: RecordInfo,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordCreateRecord {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub status: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordCreateResponse {
    pub status: Status,
    #[serde(default)]
    pub record: Option<RecordCreateRecord>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordModifyRecord {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub value: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordModifyResponse {
    pub status: Status,
    pub record: RecordModifyRecord,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordStatusRecord {
    #[serde(deserialize_with = "string_or_int::deserialize")]
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub status: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecordStatusResponse {
    pub status: Status,
    pub record: RecordStatusRecord,
}