//! Configuration with validation example.
//!
//! Run with:
//! ```bash
//! export MYAPP__PORT=8080
//! export MYAPP__API_KEY=secret123
//! cargo run --example with_validation
//! ```
//!
//! Try with invalid values:
//! ```bash
//! export MYAPP__PORT=99999  # Invalid: > 65535
//! cargo run --example with_validation
//! ```

use cfgmatic::{Config, ConfigLoader};
use serde::Deserialize;
use validator::Validate;

#[derive(Debug, Default, Deserialize, Config, Validate)]
#[config(prefix = "MYAPP")]
struct AppConfig {
    #[validate(range(min = 1, max = 65535))]
    #[config(default = "8080")]
    port: u16,

    #[validate(length(min = 10, max = 100))]
    #[config(env = "MYAPP__API_KEY")]
    api_key: String,

    #[validate(url)]
    #[config(default = "http://localhost:8080")]
    webhook_url: String,

    #[validate(range(min = 1, max = 100))]
    #[config(default = "5")]
    workers: u32,
}

fn main() {
    println!("Configuration with Validation Example");
    println!();

    // Load configuration
    let config = match AppConfig::from_env() {
        Ok(cfg) => cfg,
        Err(e) => {
            eprintln!("Failed to load configuration: {e}");
            std::process::exit(1);
        }
    };

    // Validate
    if let Err(e) = config.validate() {
        eprintln!("Validation failed:");
        for error in e.field_errors() {
            eprintln!("  - {}: {:?}", error.0, error.1);
        }
        std::process::exit(1);
    }

    println!("Configuration valid!");
    println!();
    println!("Settings:");
    println!("  Port: {}", config.port);
    println!(
        "  API Key: {}...",
        &config.api_key[..10.min(config.api_key.len())]
    );
    println!("  Webhook: {}", config.webhook_url);
    println!("  Workers: {}", config.workers);
}
