import Foundation
import Security

/// 主控端令牌安全存储（Keychain）。
///
/// refreshToken 为一次性（ses_ 前缀），安全要求高，存 Keychain；
/// accessToken 仅内存持有（掉线即失），这里不持久化。
enum TokenStore {

    private static let service = "com.ttstd.webrtccontroller"
    private static let accessKey = "access_token"
    private static let refreshKey = "refresh_token"
    private static let userKey = "username"

    // MARK: - Access Token（内存 + Keychain 双重保留，便于冷启动恢复）

    static func saveAccessToken(_ token: String) {
        save(key: accessKey, value: token)
    }

    static func loadAccessToken() -> String? {
        load(key: accessKey)
    }

    // MARK: - Refresh Token（一次性，必须持久化于 Keychain）

    static func saveRefreshToken(_ token: String) {
        save(key: refreshKey, value: token)
    }

    static func loadRefreshToken() -> String? {
        load(key: refreshKey)
    }

    static func saveUsername(_ name: String) {
        save(key: userKey, value: name)
    }

    static func loadUsername() -> String? {
        load(key: userKey)
    }

    static func clear() {
        for k in [accessKey, refreshKey, userKey] {
            let query: [CFString: Any] = [
                kSecClass: kSecClassGenericPassword,
                kSecAttrService: service,
                kSecAttrAccount: k
            ]
            SecItemDelete(query as CFDictionary)
        }
    }

    // MARK: - Private

    private static func save(key: String, value: String) {
        // 先删后存，避免重复条目。
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: key,
            kSecValueData: Data(value.utf8)
        ]
        SecItemDelete(query as CFDictionary)
        SecItemAdd(query as CFDictionary, nil)
    }

    private static func load(key: String) -> String? {
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: key,
            kSecReturnData: true,
            kSecMatchLimit: kSecMatchLimitOne
        ]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &item)
        guard status == errSecSuccess, let data = item as? Data else { return nil }
        return String(data: data, encoding: .utf8)
    }
}
