const crypto = require('crypto');

const ALGORITHM = 'aes-256-gcm';

function getKey() {
    const secret = process.env.ENCRYPTION_KEY || process.env.JWT_SECRET || 'itnexus-fallback-key';
    return crypto.createHash('sha256').update(secret).digest();
}

function encrypt(plainText) {
    if (plainText === null || plainText === undefined || plainText === '') return null;
    const iv = crypto.randomBytes(12);
    const cipher = crypto.createCipheriv(ALGORITHM, getKey(), iv);
    const encrypted = Buffer.concat([cipher.update(String(plainText), 'utf8'), cipher.final()]);
    const authTag = cipher.getAuthTag();
    return `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`;
}

function decrypt(cipherText) {
    if (!cipherText) return null;
    const parts = cipherText.split(':');
    if (parts.length !== 3) return cipherText; // unverschlüsselter Altbestand
    try {
        const [ivB64, authTagB64, dataB64] = parts;
        const decipher = crypto.createDecipheriv(ALGORITHM, getKey(), Buffer.from(ivB64, 'base64'));
        decipher.setAuthTag(Buffer.from(authTagB64, 'base64'));
        const decrypted = Buffer.concat([decipher.update(Buffer.from(dataB64, 'base64')), decipher.final()]);
        return decrypted.toString('utf8');
    } catch {
        return null;
    }
}

module.exports = { encrypt, decrypt };
