use serde::Deserialize;
use std::path::Path;

const DEFAULT_CONFIG_PATH: &str = "config.toml";

#[derive(Debug, Clone, Deserialize)]
pub struct GeneralServiceConfig {
    pub postgres_host: String,
    pub pg_database: String,
    pub postgres_user: String,
}

pub type ConfigResult<T> = Result<T, Box<dyn std::error::Error>>;

pub fn load_config(path: impl AsRef<Path>) -> ConfigResult<GeneralServiceConfig> {
    let raw = std::fs::read_to_string(path.as_ref())?;
    let config: GeneralServiceConfig = toml::from_str(&raw)?;

    if config.pg_database.trim().is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "config database is empty",
        )
        .into());
    }

    if config.postgres_user.trim().is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "config user is empty",
        )
        .into());
    }

    Ok(config)
}

pub fn load_config_default() -> ConfigResult<GeneralServiceConfig> {
    load_config(DEFAULT_CONFIG_PATH)
}
