const EnvSetting = require("../models/env.model");
const { encrypt } = require("../helper/encryptAndDcrypt");
const { loadEnv } = require("../utils/envLoader");

exports.getEnvSettings = async (req, res) => {
    try {
        const settings = await EnvSetting.getEnvSettings();
        // Return decrypted settings for the admin panel to view/edit
        return res.status(200).json({
            success: true,
            data: settings.getDecrypted()
        });
    } catch (error) {
        return res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

exports.updateEnvSettings = async (req, res) => {
    try {
        const updates = req.body;

        // Encrypt sensitive fields before saving
        // Guard against double-encryption: skip if value is already encrypted (iv:hex format),
        // is masked (********), or is empty
        const sensitiveFields = ['NODEMAILER_PASS', 'STORAGE_TOKEN', 'TWILIO_AUTH_TOKEN'];
        const isAlreadyEncrypted = (val) => {
            if (!val || typeof val !== 'string') return false;
            // Encrypted format is "hex_iv:hex_ciphertext" (32 char hex : variable hex)
            const parts = val.split(':');
            if (parts.length !== 2) return false;
            return /^[0-9a-f]{32}$/i.test(parts[0]) && /^[0-9a-f]+$/i.test(parts[1]);
        };

        sensitiveFields.forEach(field => {
            if (updates[field]) {
                // Skip if masked placeholder or already encrypted
                if (updates[field] === '********') {
                    delete updates[field]; // Don't overwrite with mask
                } else if (isAlreadyEncrypted(updates[field])) {
                    // Already encrypted, don't encrypt again
                    console.log(`⚠️ ${field} appears already encrypted, skipping re-encryption`);
                } else {
                    updates[field] = encrypt(updates[field]);
                }
            }
        });

        let settings = await EnvSetting.findOne();
        if (!settings) {
            settings = await EnvSetting.create(updates);
        } else {
            // Update existing settings
            Object.keys(updates).forEach(key => {
                settings[key] = updates[key];
            });
            await settings.save();
        }

        // Reload the environment variables in memory
        await loadEnv();

        return res.status(200).json({
            success: true,
            message: "Environment settings updated successfully",
            data: settings
        });
    } catch (error) {
        return res.status(500).json({
            success: false,
            message: error.message
        });
    }
};
