import crypto from 'crypto';

const createHash = (value) => {
    return crypto.createHash('sha256').update((typeof value === 'string' ? value : value.toString())).digest('hex');
}

function encryptData(data) {
    try {
        if (data === null || data === undefined) {
            data = '';
        }
        const cipher = crypto.createCipheriv(
            'aes-256-cbc',
            Buffer.from(process.env.ENCRYPTION_KEY, 'hex'),
            Buffer.alloc(16, 0)
        );
        let encrypted = cipher.update(data, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return encrypted;
    } catch (error) {
        console.log(error, data, process.env.ENCRYPTION_KEY, typeof data, process.env.ENCRYPTION_KEY.length);
        return '';
    }
}
 
function decryptData(data) {
    const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(process.env.ENCRYPTION_KEY, 'hex'), Buffer.alloc(16, 0));
    let decrypted = decipher.update(data, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

export { createHash, encryptData, decryptData };