import Foundation
import Security

enum KeychainService {
    private static let service = "PortfolioJournal"
    private static let pinKey = "appLockPin"

    static func savePin(_ pin: String) -> Bool {
        guard let data = pin.data(using: .utf8) else { return false }
        deletePin()
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: pinKey,
            kSecValueData: data
        ]
        return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
    }

    static func readPin() -> String? {
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: pinKey,
            kSecReturnData: true,
            kSecMatchLimit: kSecMatchLimitOne
        ]

        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        guard status == errSecSuccess,
              let data = result as? Data,
              let pin = String(data: data, encoding: .utf8) else {
            return nil
        }
        return pin
    }

    static func deletePin() {
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: pinKey
        ]
        SecItemDelete(query as CFDictionary)
    }
}
