//
//  String+Crypto.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 30/04/2024.
//

import Foundation
import CryptoKit

enum CryptoError: Error {
    case invalidUTF8
    case cantConvertUTF8
    case invalidBase64String
    case nilSeal
}

extension Data {
    
    func encrypt(pass: String) throws -> Data {
        let key = try self._createSymmetricKey(fromString: pass)
        let sealedBox = try AES.GCM.seal(self, using: key)
        if let combined = sealedBox.combined {
            return combined
        }
        throw CryptoError.nilSeal
    }

    func decryptData(pass: String) throws -> String {
        let key = try self._createSymmetricKey(fromString: pass)
        let sealedBox = try AES.GCM.SealedBox(combined: self)
        let decryptedData = try AES.GCM.open(sealedBox, using: key)
        guard let decryptedMessage = String(data: decryptedData, encoding: .utf8) else {
            throw CryptoError.invalidUTF8
        }
        return decryptedMessage
    }

    fileprivate func _createSymmetricKey(fromString keyString: String) throws -> SymmetricKey {
        guard let keyData = Data(base64Encoded: keyString) else {
            throw CryptoError.invalidBase64String
        }
        return SymmetricKey(data: keyData)
    }
    
}

