const EnvSetting = require('../models/env.model');

let envCache = {};

// Load environment variables from Database into memory
const loadEnv = async () => {
    try {
        // console.log("Loading environment variables from database...");
        const settings = await EnvSetting.getEnvSettings();
        if (settings) {
            // Log raw settings for debugging (mask actual values in production, but needed here)
            // console.log("Raw settings:", settings);

            const decrypted = settings.getDecrypted();
            // console.log("Decrypted settings:", decrypted);

            // Start with a clean cache
            envCache = {};

            // Populate process.env with database settings (DB takes precedence over .env file)
            Object.keys(decrypted).forEach(key => {
                const value = decrypted[key];
                if (value !== undefined && value !== null) {
                    // Trim string values
                    if (typeof value === 'string') {
                        const trimmedValue = value.trim();
                        process.env[key] = trimmedValue;
                        envCache[key] = trimmedValue;
                    } else {
                        process.env[key] = value;
                        envCache[key] = value;
                    }
                }
            });

            console.log("Environment variables loaded successfully from database.");
            console.log("Loaded STORAGE_TOKEN:", process.env.STORAGE_TOKEN ? "Yes (length: " + process.env.STORAGE_TOKEN.length + ")" : "NO/NULL");
        }
    } catch (error) {
        console.error("Failed to load environment variables from DB:", error);
    }
};

// Get a specific environment variable
// Fallback to process.env if not in DB (for safety during migration or dev)
const getEnv = (key) => {
    if (envCache && envCache[key] !== undefined && envCache[key] !== "") {
        return envCache[key];
    }
    return process.env[key];
};

module.exports = {
    loadEnv,
    getEnv
};
