use crate::cli::DeploymentEnvironment;
use serde_derive::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Deserialize)]
struct HagridConfigs {
    debug: HagridConfig,
    staging: HagridConfig,
    release: HagridConfig,
}

impl HagridConfigs {
    fn get_by(self, deployment_environment: DeploymentEnvironment) -> HagridConfig {
        match deployment_environment {
            DeploymentEnvironment::Development => self.debug,
            DeploymentEnvironment::Staging => self.staging,
            DeploymentEnvironment::Production => self.release,
        }
    }
}

// this is not an exact match - Rocket config has more complicated semantics
// than a plain toml file.
// see also https://github.com/SergioBenitez/Rocket/issues/228
#[derive(Deserialize, Clone)]
pub(crate) struct HagridConfig {
    _template_dir: Option<PathBuf>,
    pub(crate) keys_internal_dir: Option<PathBuf>,
    _keys_external_dir: Option<PathBuf>,
    _assets_dir: Option<PathBuf>,
    _token_dir: Option<PathBuf>,
    _tmp_dir: Option<PathBuf>,
    _maintenance_file: Option<PathBuf>,
}

pub(crate) fn load(
    file: impl AsRef<Path>,
    env: DeploymentEnvironment,
) -> std::io::Result<HagridConfig> {
    let config_data = fs::read_to_string(file)?;
    let configs: HagridConfigs = toml::from_str(&config_data)?;

    Ok(configs.get_by(env))
}
