//! Tauri commands for BibTeX export.

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

/// Result of a BibTeX export: the formatted string plus any non-fatal errors.
#[derive(Serialize)]
pub struct BibtexExportResult {
    pub bibtex: String,
    /// Warnings for references that were skipped due to missing required fields.
    pub errors: Vec<String>,
}

/// Export a list of references as BibTeX.
#[tauri::command]
pub fn export_bibtex(
    state: State<AppState>,
    reference_ids: Vec<ReferenceId>,
) -> Result<BibtexExportResult, String> {
    state.with_repo_read(|b| {
        let (bibtex, errors) = b.export_bibtex(&reference_ids)?;
        Ok(BibtexExportResult {
            bibtex,
            errors: errors.iter().map(|e| e.to_string()).collect(),
        })
    })
}

/// Export all references in a library as BibTeX.
#[tauri::command]
pub fn export_library_bibtex(
    state: State<AppState>,
    library_id: LibraryId,
) -> Result<BibtexExportResult, String> {
    state.with_repo_read(|b| {
        let (bibtex, errors) = b.export_library_bibtex(library_id)?;
        Ok(BibtexExportResult {
            bibtex,
            errors: errors.iter().map(|e| e.to_string()).collect(),
        })
    })
}
