import Foundation
import KeychainAccess

// CHANGE THIS PREFIX TO YOURS!!!
private let group: String = "U6CKGHL5VR.imt.narayana.snikket.ios"
private let path: String = "snikket.db.key"
private let service: String = "snikket"

extension Database {
    static var encryptionKey: Data {
        let keychain = Keychain(service: service, accessGroup: group)
        if let key = keychain[data: path] {
            return key
        } else {
            // Generate a random encryption key for the firs time
            var bytes = [UInt8](repeating: 0, count: 64)
            let result = SecRandomCopyBytes(kSecRandomDefault, 64, &bytes)
            guard result == errSecSuccess else {
                fatalError(file: "DB encryption can't generate a key")
            }
            let key = Data(bytes)
            keychain[data: path] = key
            return key
        }
    }
}
