use std::env;

#[derive(Debug, Clone)]
pub struct EnvironmentConfig {
    auth_url: String,
    #[allow(dead_code)]
    data_url: String,
    #[allow(dead_code)]
    admin_auth_url: String,
    #[allow(dead_code)]
    admin_data_url: String,
    #[allow(dead_code)]
    admin_requires_basic_auth: bool,
    pub environment: String,
}

impl EnvironmentConfig {
    pub fn from_env() -> Self {
        let environment = env::var("DOQIUM_ENV").unwrap_or_else(|_| "production".to_string());

        let (auth_url, data_url, admin_auth_url, admin_data_url, admin_requires_basic_auth) =
            match environment.to_lowercase().as_str() {
                "local" => (
                    "https://localhost:3000".to_string(),
                    "https://localhost:3001".to_string(),
                    "https://localhost:3000".to_string(),
                    "https://localhost:3001".to_string(),
                    false,
                ),
                "production" | "prod" => (
                    "https://api.doqium.com".to_string(),
                    "https://api.doqium.com".to_string(),
                    "https://admin.doqium.dplabs.dev".to_string(),
                    "https://admin.doqium.dplabs.dev".to_string(),
                    true,
                ),
                _ => {
                    eprintln!(
                        "Warning: Unknown environment '{}', defaulting to production",
                        environment
                    );
                    (
                        "https://api.doqium.com".to_string(),
                        "https://api.doqium.com".to_string(),
                        "https://admin.doqium.dplabs.dev".to_string(),
                        "https://admin.doqium.dplabs.dev".to_string(),
                        true,
                    )
                }
            };

        Self {
            auth_url,
            data_url,
            admin_auth_url,
            admin_data_url,
            admin_requires_basic_auth,
            environment,
        }
    }

    #[allow(dead_code)]
    pub fn auth_base_url(&self) -> String {
        self.auth_url.clone()
    }

    #[allow(dead_code)]
    pub fn data_base_url(&self) -> String {
        self.data_url.clone()
    }

    #[allow(dead_code)]
    pub fn admin_auth_base_url(&self) -> String {
        self.admin_auth_url.clone()
    }

    #[allow(dead_code)]
    pub fn admin_data_base_url(&self) -> String {
        self.admin_data_url.clone()
    }

    #[allow(dead_code)]
    pub fn admin_requires_basic_auth(&self) -> bool {
        self.admin_requires_basic_auth
    }

    pub fn auth_sessions_url(&self) -> String {
        format!("{}/auth/v1/sessions", self.auth_url)
    }

    pub fn auth_logout_url(&self) -> String {
        format!("{}/auth/v1/user/logout", self.auth_url)
    }

    pub fn should_accept_invalid_certs(&self) -> bool {
        self.environment.to_lowercase() == "local"
    }
}

#[allow(dead_code)]
pub fn get_admin_basic_auth() -> anyhow::Result<Option<(String, String)>> {
    // Check environment variable first
    if let Ok(secrets) = env::var("DOQIUM_ADMIN_SECRETS") {
        if let Some((user, pass)) = secrets.split_once(':') {
            return Ok(Some((user.to_string(), pass.to_string())));
        }
    }

    // Prompt user for credentials
    use std::io::{self, Write};

    print!("Admin username: ");
    io::stdout().flush()?;

    let mut username = String::new();
    io::stdin().read_line(&mut username)?;
    let username = username.trim().to_string();

    if username.is_empty() {
        anyhow::bail!("Username cannot be empty");
    }

    let password = rpassword::prompt_password("Admin password: ")?;

    if password.is_empty() {
        anyhow::bail!("Password cannot be empty");
    }

    Ok(Some((username, password)))
}
