use crate::db::pool;
use rusqlite::params;

/// 读取产品组的画布状态（JSON 字符串），不存在时返回 null
#[tauri::command]
pub fn get_canvas_state(group_id: String) -> Result<Option<String>, String> {
    let conn = pool().get().map_err(|e| e.to_string())?;
    match conn.query_row(
        "SELECT data FROM canvas_states WHERE group_id = ?1",
        params![group_id],
        |row| row.get::<_, String>(0),
    ) {
        Ok(data) => Ok(Some(data)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e.to_string()),
    }
}

/// 保存（覆盖）产品组的画布状态
#[tauri::command]
pub fn save_canvas_state(group_id: String, data: String) -> Result<(), String> {
    let conn = pool().get().map_err(|e| e.to_string())?;
    conn.execute(
        "INSERT OR REPLACE INTO canvas_states (group_id, data, updated_at)
         VALUES (?1, ?2, datetime('now'))",
        params![group_id, data],
    )
    .map_err(|e| e.to_string())?;
    Ok(())
}
