//
//  CCRSACipher.swift
//  punchnet
//
//  Created by 安礼成 on 2026/3/17.
//
import Foundation

struct CCRSACipher: RSACipher {
    var pubKey: String
    let privateKeyDER: Data
    
    init(keySize: Int) throws {
        let (privateKey, publicKey) = try Self.loadKeys(keySize: keySize)
        let privKeyStr = SwKeyConvert.PrivateKey.derToPKCS1PEM(privateKey)
        
        self.pubKey = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
        self.privateKeyDER = try SwKeyConvert.PrivateKey.pemToPKCS1DER(privKeyStr)
    }
    
    public func decode(data: Data) throws -> Data {
        let tag = Data()
        let (decryptedData, _) = try CC.RSA.decrypt(data, derKey: self.privateKeyDER, tag: tag, padding: .pkcs1, digest: .none)
        
        return decryptedData
    }
    
    private static func loadKeys(keySize: Int) throws -> (Data, Data) {
        if let privateKey = UserDefaults.standard.data(forKey: "privateKey"),
           let publicKey = UserDefaults.standard.data(forKey: "publicKey") {
            
            return (privateKey, publicKey)
        } else {
            let (privateKey, publicKey) = try CC.RSA.generateKeyPair(keySize)
            UserDefaults.standard.setValue(privateKey, forKey: "privateKey")
            UserDefaults.standard.setValue(publicKey, forKey: "publicKey")
            
            return (privateKey, publicKey)
        }
    }
}
