//! Tauri commands for managing PDF viewer windows.

use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};

/// Open a PDF viewer window for the given reference ID.
///
/// If a window for this reference is already open it is focused instead of
/// creating a duplicate.
///
/// The window loads `brittle://app/viewer?ref_id=<ref_id>`.
#[tauri::command]
pub fn open_pdf_window(app: AppHandle, ref_id: String) -> Result<(), String> {
    let label = format!("pdf-{}", ref_id);

    // If already open, just focus it.
    if let Some(win) = app.get_webview_window(&label) {
        win.set_focus().map_err(|e| e.to_string())?;
        return Ok(());
    }

    let url_str = format!(
        "brittle://app/viewer?ref_id={}",
        urlencoding::encode(&ref_id)
    );
    let url = url_str.parse::<url::Url>().map_err(|e| e.to_string())?;

    WebviewWindowBuilder::new(&app, &label, WebviewUrl::External(url))
        .title("PDF Viewer — Brittle")
        .inner_size(900.0, 750.0)
        .min_inner_size(600.0, 400.0)
        .build()
        .map_err(|e| e.to_string())?;

    Ok(())
}

/// Close the PDF viewer window for the given reference ID, if open.
#[tauri::command]
pub fn close_pdf_window(app: AppHandle, ref_id: String) -> Result<(), String> {
    let label = format!("pdf-{}", ref_id);
    if let Some(win) = app.get_webview_window(&label) {
        win.close().map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Return the labels of all currently open PDF viewer windows.
#[tauri::command]
pub fn list_pdf_windows(app: AppHandle) -> Vec<String> {
    app.webview_windows()
        .into_keys()
        .filter(|label| label.starts_with("pdf-"))
        .collect()
}
