const crypto = require("crypto");

// Helper to get key dynamically (since env might be loaded after this module)
const getKey = () => {
    let key = process.env.SECRET_KEY;

    // Fallback if missing (matches DB default)
    if (!key) {
        // console.warn("⚠️ SECRET_KEY missing in env. Using default fallback key.");
        key = "5f8a9e2b1c3d4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a";
    }

    // Ensure key is valid hex string of correct length
    if (key.length !== 64) {
        // If invalid length, fallback to default
        return "5f8a9e2b1c3d4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a";
    }

    return key;
};

function encrypt(text) {
    if (!text) return null;

    try {
        const ENCRYPTION_KEY = getKey();

        // Convert hex string to 32-byte buffer
        const keyBuffer = Buffer.from(ENCRYPTION_KEY, 'hex');
        const iv = crypto.randomBytes(16);

        const cipher = crypto.createCipheriv("aes-256-cbc", keyBuffer, iv);
        let encrypted = cipher.update(text, 'utf8');
        encrypted = Buffer.concat([encrypted, cipher.final()]);

        // Return IV + encrypted data as hex
        return iv.toString("hex") + ":" + encrypted.toString("hex");
    } catch (error) {
        console.error("Encryption failed:", error.message);
        return null;
    }
}

function decrypt(data) {
    if (!data) return null;

    try {
        const ENCRYPTION_KEY = getKey();

        // Convert hex string to 32-byte buffer
        const keyBuffer = Buffer.from(ENCRYPTION_KEY, 'hex');

        const parts = data.split(':');
        if (parts.length !== 2) return null; // Invalid format

        const [ivHex, encryptedHex] = parts;
        const iv = Buffer.from(ivHex, "hex");
        const encrypted = Buffer.from(encryptedHex, "hex");

        const decipher = crypto.createDecipheriv("aes-256-cbc", keyBuffer, iv);
        let decrypted = decipher.update(encrypted);
        decrypted = Buffer.concat([decrypted, decipher.final()]);

        return decrypted.toString('utf8');
    } catch (error) {
        // console.error("Decryption failed:", error.message);
        return null; // Return null on decryption failure (e.g. wrong key)
    }
}

module.exports = {
    encrypt,
    decrypt
};
