const crypto = require('crypto');
function decode(encryptedDataFilePath) {

    // console.log('encryptedDataFilePath :', encryptedDataFilePath);
    const privateKeyPath = process.env.PRIVATE_KEY_PATH;
    const encryptedFileContent = fs.readFileSync(encryptedDataFilePath);

  // Extract the encrypted AES key, IV, and ciphertext
  const encryptedAesKeyDec = encryptedFileContent.slice(0, 256); // Assuming 2048-bit RSA key, 256 bytes for the encrypted AES key
  const ivDec = encryptedFileContent.slice(256, 256 + 16); // IV is 16 bytes
  const ciphertext = encryptedFileContent.slice(256 + 16);

    try {
            
            // Decrypt the AES key with the private key
            const privateKeyObj = fs.readFileSync(privateKeyPath, 'utf-8');
            const decryptedAesKey = crypto.privateDecrypt(
            {
                key: privateKeyObj,
                padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
                oaepHash: 'sha256',
            },
            encryptedAesKeyDec
            );

            // Decrypt the file using AES
            // const decipher = crypto.createDecipheriv('aes-128-cbc', decryptedAesKey, ivDec);
            // let decryptedData = decipher.update(ciphertext);
            // decryptedData = Buffer.concat([decryptedData, decipher.final()]);

            const decipher = crypto.createDecipheriv('aes-128-cbc', decryptedAesKey, ivDec);
            let decryptedData = decipher.update(ciphertext, 'hex', 'utf-8');
            decryptedData += decipher.final('utf-8');

            // console.log('File decrypted successfully.');
            // console.log('Decrypted String:', decryptedData);
            return decryptedData;
            
    } catch (error) {
        
            console.error('Decryption failed:', error.message);
            return null;
    }
}

module.exports = decode;
