//! 认证状态存储
//!
//! 负责 auth.json 的读写，使用原子写入 + 文件锁 + Unix 0600 权限。

use serde::Serialize;
use serde::de::DeserializeOwned;
use tauri::AppHandle;
use crate::storage::engine::{
    atomic_write_json, with_file_lock, read_json,
    restrict_file_permissions, StorageError,
};
use crate::storage::paths::get_auth_state_path;

/// 保存认证状态
pub fn save_auth_state<T>(app: &AppHandle, state: &T) -> Result<(), StorageError>
where
    T: Serialize,
{
    let path = get_auth_state_path(app)?;
    with_file_lock(&path, || {
        atomic_write_json(&path, state)?;
        restrict_file_permissions(&path)?;
        Ok(())
    })
}

/// 加载认证状态
pub fn load_auth_state<T>(app: &AppHandle) -> Result<Option<T>, StorageError>
where
    T: DeserializeOwned,
{
    let path = get_auth_state_path(app)?;
    read_json(&path)
}

/// 清除认证状态
pub fn clear_auth_state(app: &AppHandle) -> Result<(), StorageError> {
    let path = get_auth_state_path(app)?;
    // 直接尝试删除，忽略 NotFound 错误
    match std::fs::remove_file(&path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e.into()),
    }
}
