//! 认证状态存储命令

use crate::ApiResponse;
use crate::StringResultExt;
use crate::storage::auth as auth_storage;
use tauri::Manager;

#[tauri::command]
pub async fn load_auth_state(app: tauri::AppHandle) -> ApiResponse<Option<serde_json::Value>> {
    match auth_storage::load_auth_state(&app).map_err_string() {
        Ok(data) => ApiResponse {
            code: 200,
            message: "Auth state loaded successfully".to_string(),
            data: Some(data),
        },
        Err(e) => ApiResponse {
            code: 500,
            message: format!("Failed to load auth state: {}", e),
            data: None,
        },
    }
}

#[tauri::command]
pub async fn save_auth_state(
    app: tauri::AppHandle,
    state: serde_json::Value,
) -> ApiResponse<bool> {
    match auth_storage::save_auth_state(&app, &state).map_err_string() {
        Ok(_) => {
            // 保存 auth 成功后，检查是否需要迁移旧全局数据
            // 场景：用户在退出状态下升级应用，setup 阶段跳过迁移；
            // 重新登录时触发迁移，确保旧数据正确归入当前用户目录
            if let Ok(data_dir) = app.path().app_local_data_dir() {
                if let Err(e) = crate::migrate_legacy_data(&data_dir, &app) {
                    eprintln!("[save_auth_state] 数据迁移失败: {}", e);
                }
            }
            ApiResponse {
                code: 200,
                message: "Auth state saved successfully".to_string(),
                data: Some(true),
            }
        }
        Err(e) => ApiResponse {
            code: 500,
            message: format!("Failed to save auth state: {}", e),
            data: None,
        },
    }
}

#[tauri::command]
pub async fn clear_auth_state(app: tauri::AppHandle) -> ApiResponse<bool> {
    match auth_storage::clear_auth_state(&app).map_err_string() {
        Ok(_) => ApiResponse {
            code: 200,
            message: "Auth state cleared successfully".to_string(),
            data: Some(true),
        },
        Err(e) => ApiResponse {
            code: 500,
            message: format!("Failed to clear auth state: {}", e),
            data: None,
        },
    }
}
