//! 配置相关命令

use crate::models::DeviceInfo;
use crate::state::AppState;
use crate::utils::{AppConfig, CommandResult};

/// 获取应用配置
#[tauri::command]
pub async fn get_app_config() -> CommandResult<AppConfig> {
    Ok(AppConfig::get())
}

/// 更新设备名称
#[tauri::command]
pub async fn update_device_name(name: String) -> CommandResult<()> {
    AppConfig::set_device_name(name.clone());
    
    // 更新本机设备信息
    let state = AppState::get();
    let mut device = state.local_device.write();
    device.device_name = name;
    
    Ok(())
}

/// 更新下载目录
#[tauri::command]
pub async fn update_download_dir(dir: String) -> CommandResult<()> {
    // 验证目录是否存在
    let path = std::path::PathBuf::from(&dir);
    if !path.exists() {
        std::fs::create_dir_all(&path).map_err(|e| crate::utils::CommandError {
            code: "IO_ERROR".to_string(),
            message: e.to_string(),
        })?;
    }
    
    AppConfig::set_download_dir(dir);
    Ok(())
}

/// 获取本机设备信息
#[tauri::command]
pub async fn get_local_device_info() -> CommandResult<DeviceInfo> {
    let state = AppState::get();
    state.update_local_ip();
    
    let device = state.local_device.read().clone();
    Ok(device)
}
