//
//  KeychainHelper.swift
//  iKeyMon
//
//  Created by tracer on 30.03.25.
//

import Foundation
import Security

enum KeychainHelper {
    static func saveApiKey(_ apiKey: String, for hostname: String) {
        let data = Data(apiKey.utf8)
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: hostname,
            kSecValueData as String: data
        ]

        SecItemDelete(query as CFDictionary) // Overwrite existing
        SecItemAdd(query as CFDictionary, nil)
    }

    static func loadApiKey(for hostname: String) -> String? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: hostname,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]

        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)

        if status == errSecSuccess,
           let data = result as? Data,
           let string = String(data: data, encoding: .utf8) {
            return string
        }

        return nil
    }

    static func deleteApiKey(for hostname: String) {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: hostname
        ]
        SecItemDelete(query as CFDictionary)
    }
}
