const CryptoJS = require('crypto-js');

const encryptData = (data) => {
    if (!data) return data;
    try {
        const dataString = JSON.stringify(data);
        return CryptoJS.AES.encrypt(dataString, process.env.SECRET_CRYPTO).toString();
    } catch (error) {
        console.error('Encryption error:', error);
        return data;
    }
};

const decryptData = (ciphertext) => {
    if (!ciphertext) return ciphertext;
    try {
        const bytes = CryptoJS.AES.decrypt(ciphertext, process.env.SECRET_CRYPTO);
        const originalText = bytes.toString(CryptoJS.enc.Utf8);
        return JSON.parse(originalText);
    } catch (error) {
        console.error('Decryption error:', error);
        return null;
    }
};

module.exports = {
    encryptData,
    decryptData,
};
