use directories::UserDirs;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct RegistryConfig {
    pub url: String,
    pub version: String,
}

pub(crate) fn read_registry_config() -> Option<RegistryConfig> {
    let user_dirs = UserDirs::new().unwrap();
    let config_path = user_dirs.home_dir().join(".config").join("dockertags");

    if !Path::new(&config_path).exists() {
        return None;
    }

    let config_content = fs::read_to_string(config_path).ok()?;
    let config: toml::Value = toml::from_str(&config_content).ok()?;

    if let Some(registry) = config.get("registry") {
        let url = registry.get("url")?.as_str()?.to_string();
        let version = registry.get("version")?.as_str()?.to_string();
        return Some(RegistryConfig { url, version });
    }

    None
}

pub(crate) fn write_registry_config(url: &str, version: &str) -> std::io::Result<()> {
    let user_dirs = UserDirs::new().unwrap();
    let config_path = user_dirs.home_dir().join(".config").join("dockertags");

    let registry_config = RegistryConfig {
        url: url.to_string(),
        version: version.to_string(),
    };

    let toml_content = toml::to_string(&registry_config).unwrap();
    fs::write(config_path, toml_content)
}
