import Foundation
import Security

/// Server URL and config in UserDefaults; the API token in the Keychain (this device only).
final class Settings: ObservableObject {
    static let shared = Settings()
    private let d = UserDefaults.standard

    @Published var server: String? { didSet { d.set(server, forKey: "server") } }
    @Published var configJSON: Data? { didSet { d.set(configJSON, forKey: "config") } }
    @Published var autoListen: Bool { didSet { d.set(autoListen, forKey: "auto_listen") } }
    @Published var healthEnabled: Bool { didSet { d.set(healthEnabled, forKey: "health_on") } }
    @Published var wardUHID: String { didSet { d.set(wardUHID, forKey: "ward_uhid") } }

    private init() {
        server = d.string(forKey: "server"); configJSON = d.data(forKey: "config")
        autoListen = d.bool(forKey: "auto_listen"); healthEnabled = d.bool(forKey: "health_on"); wardUHID = d.string(forKey: "ward_uhid") ?? ""
    }

    var token: String? {
        get { Keychain.read("token") }
        set { if let v = newValue { Keychain.write("token", v) } else { Keychain.delete("token") } }
    }
    var isPaired: Bool { server != nil && token != nil }
    var config: [String: Any]? { configJSON.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } }

    func glucoseSeq(_ id: String) -> Int? { d.object(forKey: "gseq_\(id)") as? Int }
    func setGlucoseSeq(_ id: String, _ v: Int) { d.set(v, forKey: "gseq_\(id)") }
    func healthAnchor(_ type: String) -> Data? { d.data(forKey: "hk_\(type)") }
    func setHealthAnchor(_ type: String, _ v: Data?) { d.set(v, forKey: "hk_\(type)") }

    func clear() {
        for k in ["server", "config", "auto_listen", "health_on", "ward_uhid"] { d.removeObject(forKey: k) }
        token = nil; server = nil; configJSON = nil; autoListen = false; healthEnabled = false; wardUHID = ""
    }
}

enum Keychain {
    private static let service = "in.caresoft.carepulse"
    static func write(_ key: String, _ value: String) {
        delete(key)
        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key,
                                kSecValueData as String: Data(value.utf8), kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]
        SecItemAdd(q as CFDictionary, nil)
    }
    static func read(_ key: String) -> String? {
        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key,
                                kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]
        var out: AnyObject?
        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }
        return String(data: d, encoding: .utf8)
    }
    static func delete(_ key: String) {
        SecItemDelete([kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key] as CFDictionary)
    }
}
