//! Tauri commands for library CRUD, hierarchy, and membership.

use crate::state::AppState;
use brittle_core::{Library, LibraryId, ReferenceId};
use tauri::State;

#[tauri::command]
pub fn create_library(
    state: State<AppState>,
    name: String,
    parent_id: Option<LibraryId>,
) -> Result<Library, String> {
    state.with_repo(|b| b.create_library(name, parent_id))
}

#[tauri::command]
pub fn get_library(state: State<AppState>, id: LibraryId) -> Result<Library, String> {
    state.with_repo_read(|b| b.get_library(id))
}

#[tauri::command]
pub fn rename_library(
    state: State<AppState>,
    id: LibraryId,
    new_name: String,
) -> Result<Library, String> {
    state.with_repo(|b| b.rename_library(id, new_name))
}

#[tauri::command]
pub fn move_library(
    state: State<AppState>,
    id: LibraryId,
    new_parent: Option<LibraryId>,
) -> Result<Library, String> {
    state.with_repo(|b| b.move_library(id, new_parent))
}

/// Delete a library. Fails if it has child libraries.
#[tauri::command]
pub fn delete_library(state: State<AppState>, id: LibraryId) -> Result<(), String> {
    state.with_repo(|b| b.delete_library(id))
}

/// Delete a library and all its descendants (recursive).
#[tauri::command]
pub fn force_delete_library(state: State<AppState>, id: LibraryId) -> Result<(), String> {
    state.with_repo(|b| b.force_delete_library(id))
}

#[tauri::command]
pub fn list_root_libraries(state: State<AppState>) -> Result<Vec<Library>, String> {
    state.with_repo_read(|b| b.list_root_libraries())
}

#[tauri::command]
pub fn list_child_libraries(
    state: State<AppState>,
    parent_id: LibraryId,
) -> Result<Vec<Library>, String> {
    state.with_repo_read(|b| b.list_child_libraries(parent_id))
}

/// Return the ancestor chain of a library, ordered root → direct parent.
#[tauri::command]
pub fn get_library_ancestors(
    state: State<AppState>,
    id: LibraryId,
) -> Result<Vec<Library>, String> {
    state.with_repo_read(|b| b.get_library_ancestors(id))
}

#[tauri::command]
pub fn add_to_library(
    state: State<AppState>,
    library_id: LibraryId,
    reference_id: ReferenceId,
) -> Result<(), String> {
    state.with_repo(|b| b.add_to_library(library_id, reference_id))
}

#[tauri::command]
pub fn remove_from_library(
    state: State<AppState>,
    library_id: LibraryId,
    reference_id: ReferenceId,
) -> Result<(), String> {
    state.with_repo(|b| b.remove_from_library(library_id, reference_id))
}

#[tauri::command]
pub fn list_reference_libraries(
    state: State<AppState>,
    reference_id: ReferenceId,
) -> Result<Vec<Library>, String> {
    state.with_repo_read(|b| b.list_reference_libraries(reference_id))
}
