manydns 1.0.0

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
//! Low-level Tencent Cloud DNSPod API client.
//!
//! This module provides direct access to the Tencent Cloud DNSPod API using
//! the TC3-HMAC-SHA256 signature algorithm.
//!
//! # API Reference
//!
//! - [API Category](https://www.tencentcloud.com/document/api/1157/49025)
//! - [Signature v3](https://www.tencentcloud.com/document/api/1157/49029)
//! - [Data Types](https://www.tencentcloud.com/document/api/1157/49043)

use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

/// The Tencent Cloud DNSPod API endpoint.
const TENCENT_API_HOST: &str = "dnspod.intl.tencentcloudapi.com";
const TENCENT_API_URL: &str = "https://dnspod.intl.tencentcloudapi.com";

/// Service name for signature calculation.
const SERVICE: &str = "dnspod";

/// API version.
const API_VERSION: &str = "2021-03-23";

/// Errors that may occur when interacting with the Tencent Cloud API.
#[derive(Debug, Error)]
pub enum TencentError {
    /// The API returned an error response.
    #[error("API error: {0}")]
    Api(ApiError),

    /// An HTTP request error occurred.
    #[error("HTTP request error: {0}")]
    Request(#[from] reqwest::Error),

    /// Failed to serialize request.
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
}

/// Tencent Cloud API error response.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiError {
    /// Error code.
    #[serde(rename = "Code")]
    pub code: String,
    /// Error message.
    #[serde(rename = "Message")]
    pub message: String,
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

/// Raw API response that can contain either an error or success data.
/// We first deserialize to this to check for errors before deserializing the actual data.
#[derive(Debug, Deserialize)]
struct RawApiResponse {
    #[serde(rename = "Response")]
    response: serde_json::Value,
}

/// Error response structure.
#[derive(Debug, Deserialize)]
struct ErrorResponse {
    #[serde(rename = "Error")]
    error: ApiError,
}

// =============================================================================
// API Request/Response Types
// =============================================================================

/// Domain list item from DescribeDomainList.
#[derive(Debug, Clone, Deserialize)]
pub struct DomainListItem {
    /// Domain ID.
    #[serde(rename = "DomainId")]
    pub domain_id: u64,
    /// Domain name.
    #[serde(rename = "Name")]
    pub name: String,
    /// Domain status.
    #[serde(rename = "Status")]
    pub status: String,
    /// TTL.
    #[serde(rename = "TTL")]
    pub ttl: u64,
    /// Record count.
    #[serde(rename = "RecordCount")]
    pub record_count: Option<u64>,
}

/// Response for DescribeDomainList.
#[derive(Debug, Deserialize)]
pub struct DescribeDomainListResponse {
    #[serde(rename = "DomainList")]
    pub domain_list: Option<Vec<DomainListItem>>,
    #[serde(rename = "DomainCountInfo")]
    pub domain_count_info: Option<DomainCountInfo>,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Domain count information.
#[derive(Debug, Deserialize)]
pub struct DomainCountInfo {
    #[serde(rename = "DomainTotal")]
    pub domain_total: u64,
    #[serde(rename = "AllTotal")]
    pub all_total: u64,
}

/// Domain info from DescribeDomain.
#[derive(Debug, Clone, Deserialize)]
pub struct DomainInfo {
    /// Domain ID.
    #[serde(rename = "DomainId")]
    pub domain_id: u64,
    /// Domain name.
    #[serde(rename = "Domain")]
    pub domain: String,
    /// Domain status.
    #[serde(rename = "Status")]
    pub status: String,
    /// TTL.
    #[serde(rename = "TTL")]
    pub ttl: u64,
    /// Record count.
    #[serde(rename = "RecordCount")]
    pub record_count: Option<u64>,
}

/// Response for DescribeDomain.
#[derive(Debug, Deserialize)]
pub struct DescribeDomainResponse {
    #[serde(rename = "DomainInfo")]
    pub domain_info: DomainInfo,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Record list item from DescribeRecordList.
#[derive(Debug, Clone, Deserialize)]
pub struct RecordListItem {
    /// Record ID.
    #[serde(rename = "RecordId")]
    pub record_id: u64,
    /// Subdomain (host record).
    #[serde(rename = "Name")]
    pub name: String,
    /// Record type.
    #[serde(rename = "Type")]
    pub record_type: String,
    /// Record value.
    #[serde(rename = "Value")]
    pub value: String,
    /// TTL.
    #[serde(rename = "TTL")]
    pub ttl: u64,
    /// Record line.
    #[serde(rename = "Line")]
    pub line: String,
    /// Record status.
    #[serde(rename = "Status")]
    pub status: String,
    /// MX priority.
    #[serde(rename = "MX")]
    pub mx: Option<u16>,
}

impl TryFrom<&RecordListItem> for crate::Record {
    type Error = RecordConversionError;

    fn try_from(item: &RecordListItem) -> Result<Self, Self::Error> {
        let data = parse_record_data(&item.record_type, &item.value, item.mx)?;
        Ok(crate::Record {
            id: item.record_id.to_string(),
            host: item.name.clone(),
            data,
            ttl: item.ttl,
        })
    }
}

impl TryFrom<RecordListItem> for crate::Record {
    type Error = RecordConversionError;

    fn try_from(item: RecordListItem) -> Result<Self, Self::Error> {
        Self::try_from(&item)
    }
}

/// Response for DescribeRecordList.
#[derive(Debug, Deserialize)]
pub struct DescribeRecordListResponse {
    #[serde(rename = "RecordList")]
    pub record_list: Option<Vec<RecordListItem>>,
    #[serde(rename = "RecordCountInfo")]
    pub record_count_info: Option<RecordCountInfo>,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Record count information.
#[derive(Debug, Deserialize)]
pub struct RecordCountInfo {
    #[serde(rename = "TotalCount")]
    pub total_count: u64,
}

/// Record info from DescribeRecord.
#[derive(Debug, Clone, Deserialize)]
pub struct RecordInfo {
    /// Record ID.
    #[serde(rename = "Id")]
    pub id: u64,
    /// Subdomain.
    #[serde(rename = "SubDomain")]
    pub sub_domain: String,
    /// Record type.
    #[serde(rename = "RecordType")]
    pub record_type: String,
    /// Record value.
    #[serde(rename = "Value")]
    pub value: String,
    /// TTL.
    #[serde(rename = "TTL")]
    pub ttl: u64,
    /// MX priority.
    #[serde(rename = "MX")]
    pub mx: Option<u16>,
    /// Record status.
    #[serde(rename = "Enabled")]
    pub enabled: u8,
}

impl TryFrom<&RecordInfo> for crate::Record {
    type Error = RecordConversionError;

    fn try_from(info: &RecordInfo) -> Result<Self, Self::Error> {
        let data = parse_record_data(&info.record_type, &info.value, info.mx)?;
        Ok(crate::Record {
            id: info.id.to_string(),
            host: info.sub_domain.clone(),
            data,
            ttl: info.ttl,
        })
    }
}

impl TryFrom<RecordInfo> for crate::Record {
    type Error = RecordConversionError;

    fn try_from(info: RecordInfo) -> Result<Self, Self::Error> {
        Self::try_from(&info)
    }
}

/// Response for DescribeRecord.
#[derive(Debug, Deserialize)]
pub struct DescribeRecordResponse {
    #[serde(rename = "RecordInfo")]
    pub record_info: RecordInfo,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Response for CreateRecord.
#[derive(Debug, Deserialize)]
pub struct CreateRecordResponse {
    #[serde(rename = "RecordId")]
    pub record_id: u64,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Response for ModifyRecord.
#[derive(Debug, Deserialize)]
pub struct ModifyRecordResponse {
    #[serde(rename = "RecordId")]
    pub record_id: u64,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Response for DeleteRecord.
#[derive(Debug, Deserialize)]
pub struct DeleteRecordResponse {
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Response for CreateDomain.
#[derive(Debug, Deserialize)]
pub struct CreateDomainResponse {
    #[serde(rename = "DomainInfo")]
    pub domain_info: DomainCreateInfo,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

/// Domain creation info.
#[derive(Debug, Clone, Deserialize)]
pub struct DomainCreateInfo {
    /// Domain ID.
    #[serde(rename = "Id")]
    pub id: u64,
    /// Domain name.
    #[serde(rename = "Domain")]
    pub domain: String,
}

/// Response for DeleteDomain.
#[derive(Debug, Deserialize)]
pub struct DeleteDomainResponse {
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

// =============================================================================
// TC3-HMAC-SHA256 Signature Implementation
// =============================================================================

/// Computes SHA256 hash and returns it as a lowercase hex string.
fn sha256_hex(data: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(data.as_bytes());
    hex::encode(hasher.finalize())
}

/// Computes HMAC-SHA256 and returns the raw bytes.
fn hmac_sha256(key: &[u8], data: &str) -> Vec<u8> {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    type HmacSha256 = Hmac<Sha256>;
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
    mac.update(data.as_bytes());
    mac.finalize().into_bytes().to_vec()
}

/// Generates the TC3-HMAC-SHA256 signature for a request.
fn generate_signature(
    secret_id: &str,
    secret_key: &str,
    timestamp: u64,
    _action: &str,
    payload: &str,
) -> (String, String) {
    // Step 1: Build canonical request
    let http_request_method = "POST";
    let canonical_uri = "/";
    let canonical_query_string = "";
    let content_type = "application/json; charset=utf-8";
    let canonical_headers = format!("content-type:{}\nhost:{}\n", content_type, TENCENT_API_HOST);
    let signed_headers = "content-type;host";
    let hashed_request_payload = sha256_hex(payload);

    let canonical_request = format!(
        "{}\n{}\n{}\n{}\n{}\n{}",
        http_request_method,
        canonical_uri,
        canonical_query_string,
        canonical_headers,
        signed_headers,
        hashed_request_payload
    );

    // Step 2: Build string to sign
    let algorithm = "TC3-HMAC-SHA256";
    let date = chrono::DateTime::from_timestamp(timestamp as i64, 0)
        .unwrap()
        .format("%Y-%m-%d")
        .to_string();
    let credential_scope = format!("{}/{}/tc3_request", date, SERVICE);
    let hashed_canonical_request = sha256_hex(&canonical_request);

    let string_to_sign = format!(
        "{}\n{}\n{}\n{}",
        algorithm, timestamp, credential_scope, hashed_canonical_request
    );

    // Step 3: Calculate signature
    let secret_date = hmac_sha256(format!("TC3{}", secret_key).as_bytes(), &date);
    let secret_service = hmac_sha256(&secret_date, SERVICE);
    let secret_signing = hmac_sha256(&secret_service, "tc3_request");
    let signature = hex::encode(hmac_sha256(&secret_signing, &string_to_sign));

    // Step 4: Build authorization header
    let authorization = format!(
        "{} Credential={}/{}, SignedHeaders={}, Signature={}",
        algorithm, secret_id, credential_scope, signed_headers, signature
    );

    (authorization, date)
}

// =============================================================================
// API Client
// =============================================================================

/// Tencent Cloud DNSPod API client.
pub struct Client {
    http_client: reqwest::Client,
    secret_id: String,
    secret_key: String,
}

impl Client {
    /// Creates a new Tencent Cloud API client.
    ///
    /// # Arguments
    ///
    /// * `secret_id` - Tencent Cloud SecretId from API key management
    /// * `secret_key` - Tencent Cloud SecretKey from API key management
    pub fn new(
        secret_id: &str,
        secret_key: &str,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let http_client = reqwest::Client::builder().build()?;

        Ok(Self {
            http_client,
            secret_id: secret_id.to_string(),
            secret_key: secret_key.to_string(),
        })
    }

    /// Makes a signed API request.
    async fn request<Req, Resp>(&self, action: &str, request: &Req) -> Result<Resp, TencentError>
    where
        Req: Serialize,
        Resp: for<'de> Deserialize<'de>,
    {
        let payload = serde_json::to_string(request)?;
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let (authorization, _date) = generate_signature(
            &self.secret_id,
            &self.secret_key,
            timestamp,
            action,
            &payload,
        );

        let mut headers = HeaderMap::new();
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("application/json; charset=utf-8"),
        );
        headers.insert("Host", HeaderValue::from_static(TENCENT_API_HOST));
        headers.insert(
            "Authorization",
            HeaderValue::from_str(&authorization).unwrap(),
        );
        headers.insert("X-TC-Action", HeaderValue::from_str(action).unwrap());
        headers.insert("X-TC-Version", HeaderValue::from_static(API_VERSION));
        headers.insert(
            "X-TC-Timestamp",
            HeaderValue::from_str(&timestamp.to_string()).unwrap(),
        );

        let response = self
            .http_client
            .post(TENCENT_API_URL)
            .headers(headers)
            .body(payload)
            .send()
            .await?;

        // First, get the raw JSON to check for errors
        let raw: RawApiResponse = response.json().await?;

        // Check if the response contains an Error field
        if let Ok(error_resp) = serde_json::from_value::<ErrorResponse>(raw.response.clone()) {
            return Err(TencentError::Api(error_resp.error));
        }

        // No error, deserialize the success response
        let data: Resp = serde_json::from_value(raw.response)?;
        Ok(data)
    }

    // =========================================================================
    // Domain APIs
    // =========================================================================

    /// Lists all domains.
    pub async fn describe_domain_list(
        &self,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> Result<DescribeDomainListResponse, TencentError> {
        #[derive(Serialize)]
        struct Request {
            #[serde(rename = "Offset", skip_serializing_if = "Option::is_none")]
            offset: Option<u32>,
            #[serde(rename = "Limit", skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
        }

        self.request("DescribeDomainList", &Request { offset, limit })
            .await
    }

    /// Gets domain information by domain name.
    pub async fn describe_domain(
        &self,
        domain: &str,
    ) -> Result<DescribeDomainResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
        }

        self.request("DescribeDomain", &Request { domain }).await
    }

    /// Gets domain information by domain ID.
    pub async fn describe_domain_by_id(
        &self,
        domain_id: u64,
    ) -> Result<DescribeDomainResponse, TencentError> {
        #[derive(Serialize)]
        struct Request {
            #[serde(rename = "DomainId")]
            domain_id: u64,
        }

        self.request("DescribeDomain", &Request { domain_id }).await
    }

    /// Creates a new domain.
    pub async fn create_domain(&self, domain: &str) -> Result<CreateDomainResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
        }

        self.request("CreateDomain", &Request { domain }).await
    }

    /// Deletes a domain.
    pub async fn delete_domain(&self, domain: &str) -> Result<DeleteDomainResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
        }

        self.request("DeleteDomain", &Request { domain }).await
    }

    // =========================================================================
    // Record APIs
    // =========================================================================

    /// Lists all records for a domain.
    pub async fn describe_record_list(
        &self,
        domain: &str,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> Result<DescribeRecordListResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
            #[serde(rename = "Offset", skip_serializing_if = "Option::is_none")]
            offset: Option<u32>,
            #[serde(rename = "Limit", skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
        }

        self.request(
            "DescribeRecordList",
            &Request {
                domain,
                offset,
                limit,
            },
        )
        .await
    }

    /// Gets a record by ID.
    pub async fn describe_record(
        &self,
        domain: &str,
        record_id: u64,
    ) -> Result<DescribeRecordResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
            #[serde(rename = "RecordId")]
            record_id: u64,
        }

        self.request("DescribeRecord", &Request { domain, record_id })
            .await
    }

    /// Creates a new record.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_record(
        &self,
        domain: &str,
        sub_domain: &str,
        record_type: &str,
        record_line: &str,
        value: &str,
        mx: Option<u16>,
        ttl: Option<u64>,
    ) -> Result<CreateRecordResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
            #[serde(rename = "SubDomain")]
            sub_domain: &'a str,
            #[serde(rename = "RecordType")]
            record_type: &'a str,
            #[serde(rename = "RecordLine")]
            record_line: &'a str,
            #[serde(rename = "Value")]
            value: &'a str,
            #[serde(rename = "MX", skip_serializing_if = "Option::is_none")]
            mx: Option<u16>,
            #[serde(rename = "TTL", skip_serializing_if = "Option::is_none")]
            ttl: Option<u64>,
        }

        self.request(
            "CreateRecord",
            &Request {
                domain,
                sub_domain,
                record_type,
                record_line,
                value,
                mx,
                ttl,
            },
        )
        .await
    }

    /// Modifies an existing record.
    #[allow(clippy::too_many_arguments)]
    pub async fn modify_record(
        &self,
        domain: &str,
        record_id: u64,
        sub_domain: &str,
        record_type: &str,
        record_line: &str,
        value: &str,
        mx: Option<u16>,
        ttl: Option<u64>,
    ) -> Result<ModifyRecordResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
            #[serde(rename = "RecordId")]
            record_id: u64,
            #[serde(rename = "SubDomain")]
            sub_domain: &'a str,
            #[serde(rename = "RecordType")]
            record_type: &'a str,
            #[serde(rename = "RecordLine")]
            record_line: &'a str,
            #[serde(rename = "Value")]
            value: &'a str,
            #[serde(rename = "MX", skip_serializing_if = "Option::is_none")]
            mx: Option<u16>,
            #[serde(rename = "TTL", skip_serializing_if = "Option::is_none")]
            ttl: Option<u64>,
        }

        self.request(
            "ModifyRecord",
            &Request {
                domain,
                record_id,
                sub_domain,
                record_type,
                record_line,
                value,
                mx,
                ttl,
            },
        )
        .await
    }

    /// Deletes a record.
    pub async fn delete_record(
        &self,
        domain: &str,
        record_id: u64,
    ) -> Result<DeleteRecordResponse, TencentError> {
        #[derive(Serialize)]
        struct Request<'a> {
            #[serde(rename = "Domain")]
            domain: &'a str,
            #[serde(rename = "RecordId")]
            record_id: u64,
        }

        self.request("DeleteRecord", &Request { domain, record_id })
            .await
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Error returned when a record cannot be converted to a [`crate::Record`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordConversionError {
    /// The record type that failed to convert.
    pub record_type: String,
    /// Description of what went wrong.
    pub reason: &'static str,
}

impl std::fmt::Display for RecordConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "failed to convert {} record: {}",
            self.record_type, self.reason
        )
    }
}

impl std::error::Error for RecordConversionError {}

/// Parses a record value string into [`crate::RecordData`].
fn parse_record_data(
    record_type: &str,
    value: &str,
    mx: Option<u16>,
) -> Result<crate::RecordData, RecordConversionError> {
    use crate::RecordData;

    match record_type {
        "A" => value
            .parse()
            .map(RecordData::A)
            .map_err(|_| RecordConversionError {
                record_type: record_type.to_string(),
                reason: "invalid IPv4 address",
            }),
        "AAAA" => value
            .parse()
            .map(RecordData::AAAA)
            .map_err(|_| RecordConversionError {
                record_type: record_type.to_string(),
                reason: "invalid IPv6 address",
            }),
        "CNAME" => Ok(RecordData::CNAME(value.trim_end_matches('.').to_string())),
        "MX" => Ok(RecordData::MX {
            priority: mx.unwrap_or(10),
            mail_server: value.trim_end_matches('.').to_string(),
        }),
        "NS" => Ok(RecordData::NS(value.trim_end_matches('.').to_string())),
        "TXT" => Ok(RecordData::TXT(value.trim_matches('"').to_string())),
        "SRV" => {
            // SRV format: "priority weight port target"
            let parts: Vec<&str> = value.split_whitespace().collect();
            if parts.len() >= 4 {
                Ok(RecordData::SRV {
                    priority: parts[0].parse().map_err(|_| RecordConversionError {
                        record_type: record_type.to_string(),
                        reason: "invalid SRV priority",
                    })?,
                    weight: parts[1].parse().map_err(|_| RecordConversionError {
                        record_type: record_type.to_string(),
                        reason: "invalid SRV weight",
                    })?,
                    port: parts[2].parse().map_err(|_| RecordConversionError {
                        record_type: record_type.to_string(),
                        reason: "invalid SRV port",
                    })?,
                    target: parts[3].trim_end_matches('.').to_string(),
                })
            } else {
                Err(RecordConversionError {
                    record_type: record_type.to_string(),
                    reason: "SRV record requires 4 parts: priority weight port target",
                })
            }
        }
        _ => Ok(RecordData::Other {
            typ: record_type.to_string(),
            value: value.to_string(),
        }),
    }
}