//
//  File.swift
//  
//
//  Created by Michiel Carman on 4/2/24.
//

import Foundation
import Vapor
import Crypto

enum CryptoError: Error{
    case badRequest
}

struct CustomCrypto{
    public static func DecryptString(input: String) throws -> String{
        let apikey = Environment.get("API_KEY") ?? "rv0ywT7Ygwh01jP1dQWBP39ogjq5ladO+EoNUGcBVq0="
        print(apikey)
        let base64Key = apikey // Replace with your actual key
                guard let keyData = Data(base64Encoded: base64Key) else {
                    fatalError("Invalid Base64 key data")
                }
        let data = Data(base64Encoded: input)
        let encryptionKey = SymmetricKey(data: keyData)
        let sealedBox = try! AES.GCM.SealedBox(combined: data!)
        let decryptedData = try! AES.GCM.open(sealedBox, using: encryptionKey)
        guard let decryptedString = String(data: decryptedData, encoding: .utf8) else{
            throw CryptoError.badRequest
        }
        return decryptedString
    }
    
    public static func EncryptString(input: String) throws -> String{
        let apikey = Environment.get("API_KEY") ?? "rv0ywT7Ygwh01jP1dQWBP39ogjq5ladO+EoNUGcBVq0="
        print(apikey)
        guard let keyData = Data(base64Encoded: apikey) else{
            fatalError("Invalid Base64 key data")
        }
        let encryptionKey = SymmetricKey(data: keyData)
        guard let datatoEncrypt = input.data(using: .utf8) else{ fatalError("Invalid Data")}
        do{
            let sealedBox = try AES.GCM.seal(datatoEncrypt, using: encryptionKey)
            guard let combined = sealedBox.combined else{ fatalError("Can't combine")}
            let base64EncodedString = combined.base64EncodedString()
            let urlEncodedString = base64EncodedString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
            return urlEncodedString!
        }
    }
}


