use crate::connection_manager::ConnectionManager;
use tauri::State;
use tokio::sync::Mutex;

/// Connect to an IRC server
#[tauri::command]
pub async fn connect(
    state: State<'_, Mutex<ConnectionManager>>,
    server: String,
    port: u16,
    nickname: String,
    use_tls: bool,
    app_handle: tauri::AppHandle,
) -> Result<(), String> {
    // Await the connect future while holding the lock
    println!("Connecting to {}:{} as {}", server, port, nickname);
    let mut manager = state.lock().await; // <-- .await for Tokio Mutex
    manager.connect(server, port, nickname, app_handle, use_tls).await
}

/// Disconnect from IRC
#[tauri::command]
pub fn disconnect(state: State<'_, Mutex<ConnectionManager>>) -> Result<(), String> {
    let mut manager = futures::executor::block_on(state.lock()); // <-- block_on for sync fn
    manager.disconnect()
}

/// Join a channel
#[tauri::command]
pub fn join_channel(
    state: State<'_, Mutex<ConnectionManager>>,
    channel: String
) -> Result<(), String> {
    let mut manager = futures::executor::block_on(state.lock());
    manager.join_channel(&channel)
}

/// Leave a channel
#[tauri::command]
pub fn part_channel(
    state: State<'_, Mutex<ConnectionManager>>,
    channel: String
) -> Result<(), String> {
    let mut manager = futures::executor::block_on(state.lock());
    manager.part_channel(&channel)
}

/// Send a message
#[tauri::command]
pub fn send_message(
    state: State<'_, Mutex<ConnectionManager>>,
    target: String,
    message: String
) -> Result<(), String> {
    let manager = futures::executor::block_on(state.lock());
    manager.send_message(&target, &message)
}

/// List joined channels
#[tauri::command]
pub fn list_channels(state: State<'_, Mutex<ConnectionManager>>) -> Vec<String> {
    let manager = futures::executor::block_on(state.lock());
    manager.list_channels()
}

/// Check if connected
#[tauri::command]
pub fn is_connected(state: State<'_, Mutex<ConnectionManager>>) -> bool {
    let manager = futures::executor::block_on(state.lock());
    manager.is_connected()
}
