use rusqlite::Connection;
use std::fs;
use std::path::PathBuf;

#[derive(Clone)]
pub struct AppStorage {
    #[allow(dead_code)]
    pub app_data_dir: PathBuf,
    #[allow(dead_code)]
    pub databases_dir: PathBuf,
    #[allow(dead_code)]
    pub cache_dir: PathBuf,
    pub image_cache_dir: PathBuf,
    pub users_db_path: PathBuf,
    pub library_db_path: PathBuf,
}

impl AppStorage {
    pub fn new(app_data_dir: PathBuf) -> Result<Self, String> {
        let databases_dir = app_data_dir.join("databases");
        let cache_dir = app_data_dir.join("cache");
        let image_cache_dir = cache_dir.join("images");

        fs::create_dir_all(&databases_dir)
            .map_err(|err| format!("Failed to create database directory: {err}"))?;
        fs::create_dir_all(&image_cache_dir)
            .map_err(|err| format!("Failed to create image cache directory: {err}"))?;

        Ok(Self {
            users_db_path: databases_dir.join("users.db"),
            library_db_path: databases_dir.join("library.db"),
            app_data_dir,
            databases_dir,
            cache_dir,
            image_cache_dir,
        })
    }

    pub fn connect_users(&self) -> Result<Connection, String> {
        Connection::open(&self.users_db_path)
            .map_err(|err| format!("Failed to open users database: {err}"))
    }

    pub fn connect_library(&self) -> Result<Connection, String> {
        Connection::open(&self.library_db_path)
            .map_err(|err| format!("Failed to open library database: {err}"))
    }
}
