//! Tauri commands for reference CRUD and search.

use crate::state::AppState;
use brittle_core::{EntryType, LibraryId, Reference, ReferenceId, ReferenceSummary};
use tauri::State;

#[tauri::command]
pub fn create_reference(
    state: State<AppState>,
    cite_key: String,
    entry_type: EntryType,
) -> Result<Reference, String> {
    state.with_repo(|b| b.create_reference(cite_key, entry_type))
}

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

#[tauri::command]
pub fn update_reference(state: State<AppState>, reference: Reference) -> Result<Reference, String> {
    state.with_repo(|b| b.update_reference(reference))
}

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

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

#[tauri::command]
pub fn set_field(
    state: State<AppState>,
    id: ReferenceId,
    field: String,
    value: String,
) -> Result<(), String> {
    state.with_repo(|b| b.set_field(id, &field, value))
}

#[tauri::command]
pub fn remove_field(state: State<AppState>, id: ReferenceId, field: String) -> Result<(), String> {
    state.with_repo(|b| b.remove_field(id, &field))
}

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

#[tauri::command]
pub fn search_library_references(
    state: State<AppState>,
    library_id: LibraryId,
    query: String,
) -> Result<Vec<ReferenceSummary>, String> {
    state.with_repo_read(|b| b.search_library_references(library_id, &query))
}

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

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