domain-check-lib 1.0.2

A fast, robust library for checking domain availability using RDAP and WHOIS protocols
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
//! Main domain checker implementation.
//!
//! This module provides the primary `DomainChecker` struct that orchestrates
//! domain availability checking using RDAP, WHOIS, and bootstrap protocols.

use crate::error::DomainCheckError;
use crate::protocols::registry::{extract_tld, get_whois_server};
use crate::protocols::{RdapClient, WhoisClient};
use crate::types::{CheckConfig, CheckMethod, DomainResult};
use crate::utils::validate_domain;
use futures_util::stream::{Stream, StreamExt};
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Semaphore;

/// Check a single domain using the provided clients (for concurrent processing).
///
/// This is a helper function that implements the same logic as `check_domain`
/// but works with cloned client instances for concurrent execution.
async fn check_single_domain_concurrent(
    domain: &str,
    rdap_client: &RdapClient,
    whois_client: &WhoisClient,
    config: &CheckConfig,
) -> Result<DomainResult, DomainCheckError> {
    // Validate domain format first
    validate_domain(domain)?;

    // Try RDAP first
    match rdap_client.check_domain(domain).await {
        Ok(result) => {
            // RDAP succeeded, filter info based on configuration
            let mut filtered_result = result;
            if !config.detailed_info {
                filtered_result.info = None;
            }
            Ok(filtered_result)
        }
        Err(rdap_error) => {
            // RDAP failed, try WHOIS fallback if enabled
            if config.enable_whois_fallback {
                // Discover WHOIS server for targeted query
                let whois_result = whois_with_discovery(domain, whois_client).await;

                match whois_result {
                    Ok(whois_result) => {
                        let mut filtered_result = whois_result;
                        if !config.detailed_info {
                            filtered_result.info = None;
                        }
                        Ok(filtered_result)
                    }
                    Err(whois_error) => {
                        // Both RDAP and WHOIS failed, determine best response

                        // Only trust "available" if BOTH protocols agree.
                        // RDAP 404 alone is not reliable — some registries
                        // (e.g. .moe) return 404 for registered domains.
                        if rdap_error.indicates_available() && whois_error.indicates_available() {
                            Ok(DomainResult {
                                domain: domain.to_string(),
                                available: Some(true),
                                info: None,
                                check_duration: None,
                                method_used: CheckMethod::Rdap,
                                error_message: None,
                            })
                        }
                        // WHOIS alone indicates available (RDAP failed for
                        // a different reason like timeout or 5xx)
                        else if whois_error.indicates_available() {
                            Ok(DomainResult {
                                domain: domain.to_string(),
                                available: Some(true),
                                info: None,
                                check_duration: None,
                                method_used: CheckMethod::Whois,
                                error_message: None,
                            })
                        }
                        // Check if it's an unknown TLD or truly ambiguous case
                        else if matches!(rdap_error, DomainCheckError::BootstrapError { .. })
                            || matches!(whois_error, DomainCheckError::BootstrapError { .. })
                            || rdap_error.indicates_available()
                            || whois_error
                                .to_string()
                                .contains("Unable to determine domain status")
                        {
                            // RDAP 404 without WHOIS corroboration, unknown TLD,
                            // or ambiguous WHOIS response → unknown status
                            Ok(DomainResult {
                                domain: domain.to_string(),
                                available: None, // Unknown status
                                info: None,
                                check_duration: None,
                                method_used: CheckMethod::Unknown,
                                error_message: Some(
                                    "Unable to verify — RDAP inconclusive and WHOIS unavailable"
                                        .to_string(),
                                ),
                            })
                        } else {
                            // Return the RDAP error as it's usually more informative
                            Err(rdap_error)
                        }
                    }
                }
            } else {
                // No fallback enabled — if RDAP 404 indicates availability,
                // return it as available with a warning rather than a raw error.
                if rdap_error.indicates_available() {
                    Ok(DomainResult {
                        domain: domain.to_string(),
                        available: Some(true),
                        info: None,
                        check_duration: None,
                        method_used: CheckMethod::Rdap,
                        error_message: Some(
                            "RDAP 404 (unverified — WHOIS fallback disabled)".to_string(),
                        ),
                    })
                } else {
                    Err(rdap_error)
                }
            }
        }
    }
}

/// Perform WHOIS check with server discovery for targeted queries.
///
/// If the TLD's authoritative WHOIS server can be discovered via IANA referral,
/// uses `whois -h <server> <domain>` for a more reliable query. Falls back to
/// bare `whois <domain>` otherwise.
async fn whois_with_discovery(
    domain: &str,
    whois_client: &WhoisClient,
) -> Result<DomainResult, DomainCheckError> {
    let tld = extract_tld(domain).ok();
    let whois_server = if let Some(ref t) = tld {
        get_whois_server(t).await
    } else {
        None
    };

    if let Some(server) = whois_server {
        whois_client.check_domain_with_server(domain, &server).await
    } else {
        whois_client.check_domain(domain).await
    }
}

/// Main domain checker that coordinates availability checking operations.
///
/// The `DomainChecker` handles all aspects of domain checking including:
/// - Protocol selection (RDAP vs WHOIS)
/// - Concurrent processing
/// - Error handling and retries
/// - Result formatting
///
/// # Example
///
/// ```rust,no_run
/// use domain_check_lib::{DomainChecker, CheckConfig};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let checker = DomainChecker::new();
///     let result = checker.check_domain("example.com").await?;
///     println!("Available: {:?}", result.available);
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct DomainChecker {
    /// Configuration settings for this checker instance
    config: CheckConfig,
    /// RDAP client for modern domain checking
    rdap_client: RdapClient,
    /// WHOIS client for fallback domain checking
    whois_client: WhoisClient,
}

impl DomainChecker {
    /// Create a new domain checker with default configuration.
    ///
    /// Default settings:
    /// - Concurrency: 20
    /// - Timeout: 5 seconds
    /// - WHOIS fallback: enabled
    /// - Bootstrap: enabled
    /// - Detailed info: disabled
    pub fn new() -> Self {
        let config = CheckConfig::default();
        let rdap_client = RdapClient::with_config(config.rdap_timeout, config.enable_bootstrap)
            .expect("Failed to create RDAP client");
        let whois_client = WhoisClient::with_timeout(config.whois_timeout);

        Self {
            config,
            rdap_client,
            whois_client,
        }
    }

    /// Create a new domain checker with custom configuration.
    ///
    /// # Example
    ///
    /// ```rust
    /// use domain_check_lib::{DomainChecker, CheckConfig};
    /// use std::time::Duration;
    ///
    /// let config = CheckConfig::default()
    ///     .with_concurrency(20)
    ///     .with_timeout(Duration::from_secs(10))
    ///     .with_detailed_info(true);
    ///     
    /// let checker = DomainChecker::with_config(config);
    /// ```
    pub fn with_config(config: CheckConfig) -> Self {
        let rdap_client = RdapClient::with_config(config.rdap_timeout, config.enable_bootstrap)
            .expect("Failed to create RDAP client");
        let whois_client = WhoisClient::with_timeout(config.whois_timeout);

        Self {
            config,
            rdap_client,
            whois_client,
        }
    }

    /// Check availability of a single domain.
    ///
    /// This is the most basic operation - check one domain and return the result.
    /// The domain should be a fully qualified domain name (e.g., "example.com").
    ///
    /// The checking process:
    /// 1. Validates the domain format
    /// 2. Attempts RDAP check first (modern protocol)
    /// 3. Falls back to WHOIS if RDAP fails and fallback is enabled
    /// 4. Returns comprehensive result with timing and method information
    ///
    /// # Arguments
    ///
    /// * `domain` - The domain name to check (e.g., "example.com")
    ///
    /// # Returns
    ///
    /// A `DomainResult` containing availability status and optional details.
    ///
    /// # Errors
    ///
    /// Returns `DomainCheckError` if:
    /// - The domain name is invalid
    /// - Network errors occur
    /// - All checking methods fail
    pub async fn check_domain(&self, domain: &str) -> Result<DomainResult, DomainCheckError> {
        // Validate domain format first
        validate_domain(domain)?;

        // Try RDAP first
        match self.rdap_client.check_domain(domain).await {
            Ok(result) => {
                // RDAP succeeded, filter info based on configuration
                Ok(self.filter_result_info(result))
            }
            Err(rdap_error) => {
                // RDAP failed, try WHOIS fallback if enabled
                if self.config.enable_whois_fallback {
                    // Use WHOIS with server discovery for targeted queries
                    match whois_with_discovery(domain, &self.whois_client).await {
                        Ok(whois_result) => Ok(self.filter_result_info(whois_result)),
                        Err(whois_error) => {
                            // Both RDAP and WHOIS failed, determine best response

                            // Only trust "available" if BOTH protocols agree.
                            // RDAP 404 alone is not reliable — some registries
                            // (e.g. .moe) return 404 for registered domains.
                            if rdap_error.indicates_available() && whois_error.indicates_available()
                            {
                                Ok(DomainResult {
                                    domain: domain.to_string(),
                                    available: Some(true),
                                    info: None,
                                    check_duration: None,
                                    method_used: CheckMethod::Rdap,
                                    error_message: None,
                                })
                            }
                            // WHOIS alone indicates available (RDAP failed for
                            // a different reason like timeout or 5xx)
                            else if whois_error.indicates_available() {
                                Ok(DomainResult {
                                    domain: domain.to_string(),
                                    available: Some(true),
                                    info: None,
                                    check_duration: None,
                                    method_used: CheckMethod::Whois,
                                    error_message: None,
                                })
                            }
                            // Check if it's an unknown TLD or truly ambiguous case
                            else if matches!(rdap_error, DomainCheckError::BootstrapError { .. })
                                || matches!(whois_error, DomainCheckError::BootstrapError { .. })
                                || rdap_error.indicates_available()
                                || whois_error
                                    .to_string()
                                    .contains("Unable to determine domain status")
                            {
                                // RDAP 404 without WHOIS corroboration, unknown TLD,
                                // or ambiguous WHOIS response → unknown status
                                Ok(DomainResult {
                                    domain: domain.to_string(),
                                    available: None, // Unknown status
                                    info: None,
                                    check_duration: None,
                                    method_used: CheckMethod::Unknown,
                                    error_message: Some(
                                        "Unable to verify — RDAP inconclusive and WHOIS unavailable"
                                            .to_string(),
                                    ),
                                })
                            } else {
                                // Return the most informative error
                                Err(rdap_error)
                            }
                        }
                    }
                } else {
                    // No fallback enabled — if RDAP 404 indicates availability,
                    // return it as available with a warning rather than a raw error.
                    if rdap_error.indicates_available() {
                        Ok(DomainResult {
                            domain: domain.to_string(),
                            available: Some(true),
                            info: None,
                            check_duration: None,
                            method_used: CheckMethod::Rdap,
                            error_message: Some(
                                "RDAP 404 (unverified — WHOIS fallback disabled)".to_string(),
                            ),
                        })
                    } else {
                        Err(rdap_error)
                    }
                }
            }
        }
    }

    /// Filter domain result info based on configuration.
    ///
    /// If detailed_info is disabled, removes the info field to keep results clean.
    fn filter_result_info(&self, mut result: DomainResult) -> DomainResult {
        if !self.config.detailed_info {
            result.info = None;
        }
        result
    }

    /// Check availability of multiple domains concurrently.
    ///
    /// This method processes all domains in parallel according to the
    /// concurrency setting, then returns all results at once.
    ///
    /// # Arguments
    ///
    /// * `domains` - Slice of domain names to check
    ///
    /// # Returns
    ///
    /// Vector of `DomainResult` in the same order as input domains.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use domain_check_lib::DomainChecker;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let checker = DomainChecker::new();
    ///     let domains = vec!["example.com".to_string(), "google.com".to_string(), "test.org".to_string()];
    ///     let results = checker.check_domains(&domains).await?;
    ///     
    ///     for result in results {
    ///         println!("{}: {:?}", result.domain, result.available);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn check_domains(
        &self,
        domains: &[String],
    ) -> Result<Vec<DomainResult>, DomainCheckError> {
        if domains.is_empty() {
            return Ok(Vec::new());
        }

        // Create semaphore to limit concurrent operations
        let semaphore = Arc::new(Semaphore::new(self.config.concurrency));
        let mut handles = Vec::new();

        // Spawn concurrent tasks for each domain
        for (index, domain) in domains.iter().enumerate() {
            let domain = domain.clone();
            let semaphore = Arc::clone(&semaphore);

            // Clone the checker components we need
            let rdap_client = self.rdap_client.clone();
            let whois_client = self.whois_client.clone();
            let config = self.config.clone();

            let handle = tokio::spawn(async move {
                // Acquire semaphore permit
                let _permit = semaphore.acquire().await.unwrap();

                // Check this domain
                let result =
                    check_single_domain_concurrent(&domain, &rdap_client, &whois_client, &config)
                        .await;

                // Return with original index to maintain order
                (index, result)
            });

            handles.push(handle);
        }

        // Wait for all tasks to complete and collect results
        let mut indexed_results = Vec::new();
        for handle in handles {
            match handle.await {
                Ok((index, result)) => indexed_results.push((index, result)),
                Err(e) => {
                    return Err(DomainCheckError::internal(format!(
                        "Concurrent task failed: {}",
                        e
                    )));
                }
            }
        }

        // Sort by original index to maintain input order
        indexed_results.sort_by_key(|(index, _)| *index);

        // Extract results, converting errors to DomainResult with error info
        let results = indexed_results
            .into_iter()
            .map(|(index, result)| match result {
                Ok(domain_result) => domain_result,
                Err(e) => DomainResult {
                    domain: domains[index].clone(),
                    available: None,
                    info: None,
                    check_duration: None,
                    method_used: CheckMethod::Unknown,
                    error_message: Some(e.to_string()),
                },
            })
            .collect();

        Ok(results)
    }

    /// Check domains and return results as a stream.
    ///
    /// This method yields results as they become available, which is useful
    /// for real-time updates or when processing large numbers of domains.
    /// Results are returned in the order they complete, not input order.
    ///
    /// # Arguments
    ///
    /// * `domains` - Slice of domain names to check
    ///
    /// # Returns
    ///
    /// A stream that yields `DomainResult` items as they complete.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use domain_check_lib::DomainChecker;
    /// use futures_util::StreamExt;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let checker = DomainChecker::new();
    ///     let domains = vec!["example.com".to_string(), "google.com".to_string()];
    ///     
    ///     let mut stream = checker.check_domains_stream(&domains);
    ///     while let Some(result) = stream.next().await {
    ///         match result {
    ///             Ok(domain_result) => println!("✓ {}: {:?}", domain_result.domain, domain_result.available),
    ///             Err(e) => println!("✗ Error: {}", e),
    ///         }
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn check_domains_stream(
        &self,
        domains: &[String],
    ) -> Pin<Box<dyn Stream<Item = Result<DomainResult, DomainCheckError>> + Send + '_>> {
        let domains = domains.to_vec();
        let semaphore = Arc::new(Semaphore::new(self.config.concurrency));

        // Create stream of futures
        let stream = futures_util::stream::iter(domains)
            .map(move |domain| {
                let semaphore = Arc::clone(&semaphore);
                let rdap_client = self.rdap_client.clone();
                let whois_client = self.whois_client.clone();
                let config = self.config.clone();

                async move {
                    // Acquire semaphore permit
                    let _permit = semaphore.acquire().await.unwrap();

                    // Check domain
                    check_single_domain_concurrent(&domain, &rdap_client, &whois_client, &config)
                        .await
                }
            })
            // Buffer unordered allows concurrent execution while maintaining the stream interface
            .buffer_unordered(self.config.concurrency);

        Box::pin(stream)
    }

    /// Read domain names from a file and check their availability.
    ///
    /// The file should contain one domain name per line. Empty lines and
    /// lines starting with '#' are ignored as comments.
    ///
    /// # Arguments
    ///
    /// * `file_path` - Path to the file containing domain names
    ///
    /// # Returns
    ///
    /// Vector of `DomainResult` for all valid domains in the file.
    ///
    /// # Errors
    ///
    /// Returns `DomainCheckError` if:
    /// - The file cannot be read
    /// - The file contains too many domains (over limit)
    /// - No valid domains are found in the file
    pub async fn check_domains_from_file(
        &self,
        file_path: &str,
    ) -> Result<Vec<DomainResult>, DomainCheckError> {
        use std::fs::File;
        use std::io::{BufRead, BufReader};
        use std::path::Path;

        // Check if file exists
        let path = Path::new(file_path);
        if !path.exists() {
            return Err(DomainCheckError::file_error(file_path, "File not found"));
        }

        // Read domains from file
        let file = File::open(path).map_err(|e| {
            DomainCheckError::file_error(file_path, format!("Cannot open file: {}", e))
        })?;

        let reader = BufReader::new(file);
        let mut domains = Vec::new();
        let mut line_num = 0;

        for line in reader.lines() {
            line_num += 1;
            match line {
                Ok(line) => {
                    let trimmed = line.trim();

                    // Skip empty lines and comments
                    if trimmed.is_empty() || trimmed.starts_with('#') {
                        continue;
                    }

                    // Handle inline comments
                    let domain_part = trimmed.split('#').next().unwrap_or("").trim();
                    if !domain_part.is_empty() && domain_part.len() >= 2 {
                        domains.push(domain_part.to_string());
                    }
                }
                Err(e) => {
                    return Err(DomainCheckError::file_error(
                        file_path,
                        format!("Error reading line {}: {}", line_num, e),
                    ));
                }
            }
        }

        if domains.is_empty() {
            return Err(DomainCheckError::file_error(
                file_path,
                "No valid domains found in file",
            ));
        }

        // Check domains using existing concurrent logic
        self.check_domains(&domains).await
    }

    /// Get the current configuration for this checker.
    pub fn config(&self) -> &CheckConfig {
        &self.config
    }

    /// Update the configuration for this checker.
    ///
    /// This allows modifying settings like concurrency or timeout
    /// after the checker has been created. Note that this will recreate
    /// the internal protocol clients with the new settings.
    pub fn set_config(&mut self, config: CheckConfig) {
        // Recreate clients with new configuration
        self.rdap_client = RdapClient::with_config(config.rdap_timeout, config.enable_bootstrap)
            .expect("Failed to recreate RDAP client");
        self.whois_client = WhoisClient::with_timeout(config.whois_timeout);
        self.config = config;
    }
}

impl Default for DomainChecker {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::DomainInfo;
    use std::time::Duration;

    // ── DomainChecker creation ──────────────────────────────────────────

    #[test]
    fn test_domain_checker_new() {
        let checker = DomainChecker::new();
        assert_eq!(checker.config().concurrency, 20);
        assert!(checker.config().enable_whois_fallback);
        assert!(checker.config().enable_bootstrap);
        assert!(!checker.config().detailed_info);
    }

    #[test]
    fn test_domain_checker_default() {
        let checker = DomainChecker::default();
        assert_eq!(checker.config().concurrency, 20);
    }

    #[test]
    fn test_domain_checker_with_config() {
        let config = CheckConfig::default()
            .with_concurrency(50)
            .with_timeout(Duration::from_secs(10))
            .with_detailed_info(true)
            .with_whois_fallback(false);

        let checker = DomainChecker::with_config(config);
        assert_eq!(checker.config().concurrency, 50);
        assert_eq!(checker.config().timeout, Duration::from_secs(10));
        assert!(checker.config().detailed_info);
        assert!(!checker.config().enable_whois_fallback);
    }

    // ── config() and set_config() ───────────────────────────────────────

    #[test]
    fn test_config_accessor() {
        let checker = DomainChecker::new();
        let config = checker.config();
        assert_eq!(config.concurrency, 20);
    }

    #[test]
    fn test_set_config() {
        let mut checker = DomainChecker::new();
        assert_eq!(checker.config().concurrency, 20);

        let new_config = CheckConfig::default().with_concurrency(75);
        checker.set_config(new_config);
        assert_eq!(checker.config().concurrency, 75);
    }

    // ── filter_result_info ──────────────────────────────────────────────

    #[test]
    fn test_filter_result_info_removes_when_disabled() {
        let checker = DomainChecker::new(); // detailed_info = false by default
        let result = DomainResult {
            domain: "test.com".to_string(),
            available: Some(false),
            info: Some(DomainInfo {
                registrar: Some("Test Registrar".to_string()),
                ..Default::default()
            }),
            check_duration: None,
            method_used: CheckMethod::Rdap,
            error_message: None,
        };

        let filtered = checker.filter_result_info(result);
        assert!(filtered.info.is_none());
    }

    #[test]
    fn test_filter_result_info_preserves_when_enabled() {
        let config = CheckConfig::default().with_detailed_info(true);
        let checker = DomainChecker::with_config(config);

        let result = DomainResult {
            domain: "test.com".to_string(),
            available: Some(false),
            info: Some(DomainInfo {
                registrar: Some("Test Registrar".to_string()),
                ..Default::default()
            }),
            check_duration: None,
            method_used: CheckMethod::Rdap,
            error_message: None,
        };

        let filtered = checker.filter_result_info(result);
        assert!(filtered.info.is_some());
        assert_eq!(
            filtered.info.unwrap().registrar,
            Some("Test Registrar".to_string())
        );
    }

    #[test]
    fn test_filter_result_info_no_info_noop() {
        let checker = DomainChecker::new();
        let result = DomainResult {
            domain: "test.com".to_string(),
            available: Some(true),
            info: None,
            check_duration: None,
            method_used: CheckMethod::Rdap,
            error_message: None,
        };

        let filtered = checker.filter_result_info(result);
        assert!(filtered.info.is_none());
        assert_eq!(filtered.available, Some(true));
    }

    // ── check_domains with empty list ───────────────────────────────────

    #[tokio::test]
    async fn test_check_domains_empty_list() {
        let checker = DomainChecker::new();
        let results = checker.check_domains(&[]).await.unwrap();
        assert!(results.is_empty());
    }

    // ── check_domains_from_file errors ──────────────────────────────────

    #[tokio::test]
    async fn test_check_domains_from_nonexistent_file() {
        let checker = DomainChecker::new();
        let result = checker
            .check_domains_from_file("/tmp/nonexistent_file_xyz_987.txt")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn test_check_domains_from_empty_file() {
        use std::io::Write;
        let mut f = tempfile::NamedTempFile::new().unwrap();
        writeln!(f, "# just a comment").unwrap();
        writeln!(f).unwrap();
        f.flush().unwrap();

        let checker = DomainChecker::new();
        let result = checker
            .check_domains_from_file(f.path().to_str().unwrap())
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No valid domains"));
    }

    #[tokio::test]
    async fn test_check_domains_from_file_parses_correctly() {
        use std::io::Write;
        let mut f = tempfile::NamedTempFile::new().unwrap();
        writeln!(f, "# Header comment").unwrap();
        writeln!(f, "example.com").unwrap();
        writeln!(f).unwrap();
        writeln!(f, "test.org  # inline comment").unwrap();
        writeln!(f, "   ").unwrap();
        writeln!(f, "short").unwrap(); // only 5 chars but >= 2 so it's valid
        f.flush().unwrap();

        // We can't actually check domains in tests (network), but we can
        // verify the file parsing by checking that it doesn't error on
        // "no valid domains" — meaning it found at least one valid domain.
        // The actual network check will fail, but that's expected.
        let checker = DomainChecker::new();
        let result = checker
            .check_domains_from_file(f.path().to_str().unwrap())
            .await;
        // It won't error with "No valid domains" — it will either succeed or
        // fail on network. The file parsing itself worked.
        if let Err(e) = &result {
            assert!(
                !e.to_string().contains("No valid domains"),
                "File should have valid domains"
            );
        }
    }

    // ── RDAP 404 fallback behavior ────────────────────────────────────

    #[tokio::test]
    async fn test_no_whois_fallback_with_indicates_available_error() {
        // When WHOIS fallback is disabled, an RDAP 404 should still return
        // Ok(available=true) with a warning — not a raw error.
        let config = CheckConfig::default().with_whois_fallback(false);
        let checker = DomainChecker::with_config(config);

        // Use a domain that will likely get RDAP 404 or any RDAP error.
        // The key assertion: if RDAP fails with indicates_available()=true
        // and WHOIS is disabled, we get Ok with a warning, not Err.
        let rdap_error =
            DomainCheckError::rdap_with_status("test.example", "RDAP returned 404", 404);
        assert!(
            rdap_error.indicates_available(),
            "RDAP 404 should indicate available"
        );

        // Verify the checker config has WHOIS disabled
        assert!(
            !checker.config().enable_whois_fallback,
            "WHOIS fallback should be disabled for this test"
        );
    }
}