import Foundation
import Security
import NucleicProtocol

/// Persists the Mac host's long-term `DeviceIdentity` in the login Keychain (SYNC §4.1).
/// Generated once and reused, so paired iPhones keep recognizing this Mac across launches.
public enum HostIdentityStore {
    private static let account = "com.nucleic.host.identity"

    public static func loadOrCreate() -> DeviceIdentity {
        if let data = read(), let identity = try? DeviceIdentity(importingRaw: data) {
            return identity
        }
        let identity = DeviceIdentity()
        write(identity.exportRaw())
        return identity
    }

    private static func read() -> Data? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne,
        ]
        var item: CFTypeRef?
        guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess else { return nil }
        return item as? Data
    }

    private static func write(_ data: Data) {
        SecItemDelete([
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account,
        ] as CFDictionary)
        SecItemAdd([
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account,
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,
        ] as CFDictionary, nil)
    }
}
