//
//  KeyedEncodingContainer+Extensions.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 18/09/2024.
//

import Foundation
import LeStorage

extension KeyedDecodingContainer {
    
    func decodeEncrypted(key: Key) throws -> String {
        let data = try self.decode(Data.self, forKey: key)
        return try data.decryptData(pass: CryptoKey.pass.rawValue)
    }
    
    func decodeEncryptedIfPresent(key: Key) throws -> String? {
        let data = try self.decodeIfPresent(Data.self, forKey: key)
        if let data {
            return try data.decryptData(pass: CryptoKey.pass.rawValue)
        }
        return nil
    }
    
}

extension KeyedEncodingContainer {
    
    mutating func encodeAndEncrypt(_ value: Data, forKey key: Key) throws {
        let encryped: Data = try value.encrypt(pass: CryptoKey.pass.rawValue)
        try self.encode(encryped, forKey: key)
    }

    mutating func encodeAndEncryptIfPresent(_ value: Data?, forKey key: Key) throws {
        guard let value else {
            try encodeNil(forKey: key)
            return
        }
        try self.encodeAndEncrypt(value, forKey: key)
    }
    
}


