use std::sync::Arc;

use serde::{de::DeserializeOwned, Deserialize};
use toml::de::Error;

#[derive(Deserialize, Clone)]
pub struct DatabaseConfig {
    pub connection_string: String,
    pub redis_url: String,
}

#[derive(Deserialize, Clone)]
pub struct RegionConfig {
    pub name: String,
    pub dev_sdk_account: bool,
}

#[derive(Deserialize, Clone)]
pub struct IpString(pub Arc<str>);

#[derive(Deserialize, Clone)]
pub struct AppConfig {
    pub app_id: u32,
    pub inner_ip: IpString,
}

pub fn load_or_create_config<T>(path: &str, defaults: &str) -> Result<T, Error>
where
    T: DeserializeOwned,
{
    let data = std::fs::read_to_string(path).map_or_else(
        |_| {
            std::fs::write(path, defaults).unwrap();
            defaults.to_string()
        },
        |data| data,
    );

    toml::from_str(&data)
}
