//! 通用应用设置 KV IPC — 前端 localStorage 迁移目标
//!
//! 4 个 command 读写 `app_settings` 表(key/value JSON 字符串),承载主题、面板折叠态、
//! 最近使用项等前端持久化偏好。返回统一 `Result<T, String>`。

use std::collections::HashMap;

use tauri::State;

use crate::state::AppState;

use super::err_str;

/// 取单个 key 的值(JSON 字符串),不存在返回 None
#[tauri::command]
pub async fn settings_get(
    state: State<'_, AppState>,
    key: String,
) -> Result<Option<String>, String> {
    state.settings.get(&key).await.map_err(err_str)
}

/// 写 key/value(`INSERT OR REPLACE`),刷新 updated_at
#[tauri::command]
pub async fn settings_set(
    state: State<'_, AppState>,
    key: String,
    value: String,
) -> Result<bool, String> {
    state.settings.set(&key, &value).await.map_err(err_str)
}

/// 取全部 key/value(前端启动时一次性拉回恢复偏好)
#[tauri::command]
pub async fn settings_get_all(
    state: State<'_, AppState>,
) -> Result<HashMap<String, String>, String> {
    let rows = state.settings.get_all().await.map_err(err_str)?;
    Ok(rows.into_iter().collect())
}

/// 删除单个 key
#[tauri::command]
pub async fn settings_delete(
    state: State<'_, AppState>,
    key: String,
) -> Result<bool, String> {
    state.settings.delete(&key).await.map_err(err_str)
}
