use super::{Database, DatabaseError, entities::Library, queries};
use rusqlite::params;

impl Database {
    db_query_all!(fn find_libraries_by_media_type(media_type: &str) -> Vec<Library>, queries::find_libraries_by_media_type);
    db_query_opt!(fn find_library_by_root_path(root_path: &str) -> Option<Library>, queries::find_library_by_root_path);

    pub fn create_library(
        &mut self,
        name: &str,
        root_path: &str,
        media_type: &str,
    ) -> Result<i64, DatabaseError> {
        let (_, id) = self.exec_cmd(
            &queries::create_library,
            params![name, root_path, media_type],
        )?;
        Ok(id)
    }

    pub fn find_or_create_library(
        &mut self,
        root_path: &str,
        media_type: &str,
    ) -> Result<i64, DatabaseError> {
        if let Some(lib) = self.find_library_by_root_path(root_path)? {
            return Ok(lib.id);
        }
        let name = std::path::Path::new(root_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| root_path.to_string());
        self.create_library(&name, root_path, media_type)
    }
}
