//! Export functionality for domain check results

use crate::error::{LazyDomainError, Result};
use crate::types::CheckResult;
use std::path::Path;

/// Exports results to JSON format
///
/// # Arguments
/// * `results` - The check results to export
/// * `path` - The file path to write to
///
/// # Errors
/// Returns error if serialization or file writing fails
pub fn export_json(results: &[CheckResult], path: &Path) -> Result<()> {
    let json = serde_json::to_string_pretty(results)
        .map_err(|e| LazyDomainError::SerializationError(e.to_string()))?;
    
    std::fs::write(path, json)?;
    
    Ok(())
}

/// Exports results to CSV format
///
/// # Arguments
/// * `results` - The check results to export
/// * `path` - The file path to write to
///
/// # Errors
/// Returns error if CSV writing fails
#[allow(dead_code)]
pub fn export_csv(results: &[CheckResult], path: &Path) -> Result<()> {
    let mut wtr = csv::Writer::from_path(path)
        .map_err(|e| LazyDomainError::SerializationError(e.to_string()))?;

    // Write header
    wtr.write_record(["Domain", "TLD", "Status", "Registrar", "Expiry Date", "Error Message", "Checked At"])
        .map_err(|e| LazyDomainError::SerializationError(e.to_string()))?;

    // Write data
    for result in results {
        wtr.write_record([
            &result.domain,
            &result.tld,
            &format!("{:?}", result.status),
            &result.registrar.clone().unwrap_or_default(),
            &result.expiry_date.as_ref().map(|d| d.to_rfc3339()).unwrap_or_default(),
            &result.error_message.clone().unwrap_or_default(),
            &result.checked_at.to_rfc3339(),
        ])
        .map_err(|e| LazyDomainError::SerializationError(e.to_string()))?;
    }

    wtr.flush()
        .map_err(|e| LazyDomainError::SerializationError(e.to_string()))?;

    Ok(())
}
