//! quicproquo native GUI (Tauri 2).
//!
//! The backend runs on a dedicated thread with a tokio LocalSet; all server-facing
//! work (capnp-rpc, node_service::Client) is dispatched there. Tauri commands
//! block on the request-response channel until the backend returns.

mod backend;

use std::path::PathBuf;
use std::sync::mpsc;

use backend::{spawn_backend, BackendCommand};

/// Shared state: sender to the backend thread.
struct BackendState {
    tx: mpsc::Sender<(BackendCommand, mpsc::Sender<backend::BackendResponse>)>,
}

/// Runs whoami on the backend thread and returns JSON string (identity_key, fingerprint, etc.).
#[tauri::command]
fn whoami(
    state: tauri::State<BackendState>,
    state_path: String,
    password: Option<String>,
) -> Result<String, String> {
    let (reply_tx, reply_rx) = mpsc::channel();
    state
        .tx
        .send((
            BackendCommand::Whoami {
                state_path,
                password,
            },
            reply_tx,
        ))
        .map_err(|e| e.to_string())?;
    reply_rx.recv().map_err(|e| e.to_string())?
}

/// Runs health check on the backend thread (LocalSet::run_until) and returns status JSON.
#[tauri::command]
fn health(
    state: tauri::State<BackendState>,
    server: String,
    ca_cert: Option<String>,
    server_name: Option<String>,
) -> Result<String, String> {
    let ca_cert = ca_cert
        .map(PathBuf::from)
        .unwrap_or_else(backend::default_ca_cert);
    let server_name = server_name.unwrap_or_else(backend::default_server_name);
    let (reply_tx, reply_rx) = mpsc::channel();
    state
        .tx
        .send((
            BackendCommand::Health {
                server,
                ca_cert,
                server_name,
            },
            reply_tx,
        ))
        .map_err(|e| e.to_string())?;
    reply_rx.recv().map_err(|e| e.to_string())?
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let (backend_tx, _backend_handle) = spawn_backend();

    tauri::Builder::default()
        .manage(BackendState { tx: backend_tx })
        .invoke_handler(tauri::generate_handler![whoami, health])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
