const crypto = require('crypto');

const ALGORITHM = 'aes-256-cbc';
const SECRET = crypto
    .createHash('sha256')
    .update('PLUSFIT_SUPER_SECRET_KEY')
    .digest();

/**
 * Verschlüsselt Text (neu)
 */
function encrypt(text) {
    if (!text) return null;

    // Bereits verschlüsselt? → nicht doppelt verschlüsseln
    if (text.includes(':')) return text;

    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv(ALGORITHM, SECRET, iv);

    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');

    return iv.toString('hex') + ':' + encrypted;
}

/**
 * Entschlüsselt Text (abwärtskompatibel!)
 */
function decrypt(text) {
    if (!text) return null;

    // ALTER KLARTEXT → einfach zurückgeben
    if (!text.includes(':')) {
        return text;
    }

    try {
        const [ivHex, encrypted] = text.split(':');

        const iv = Buffer.from(ivHex, 'hex');
        if (iv.length !== 16) {
            return text; // Sicherheitsfallback
        }

        const decipher = crypto.createDecipheriv(ALGORITHM, SECRET, iv);

        let decrypted = decipher.update(encrypted, 'hex', 'utf8');
        decrypted += decipher.final('utf8');

        return decrypted;
    } catch (err) {
        console.error('Decrypt-Fehler:', err.message);
        return text; // NIEMALS crashen
    }
}

module.exports = { encrypt, decrypt };
