// config/mpesaConfig.js
require('dotenv').config();

// Required variables
const required = [
    'MPESA_CONSUMER_KEY',
    'MPESA_CONSUMER_SECRET',
    'MPESA_PASSKEY',
    'MPESA_SHORTCODE',
    'MPESA_CALLBACK_URL',
];

// Fallback sandbox values
const fallbackConfig = {
    MPESA_ENVIRONMENT: 'sandbox',
    MPESA_CONSUMER_KEY: 'AJt0x0m5LFz8YYlVFihBMoYKricXpdcAVreEHDulcOKGwrGm',
    MPESA_CONSUMER_SECRET: 'CsYNRlRsGDvw6AhLV52CT2bpV29Sdks78dGVzwWVASaCwbJe6oNcgaGsPV4eTQBd',
    MPESA_PASSKEY: 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919',
    MPESA_SHORTCODE: '174379',
    MPESA_CALLBACK_URL: 'https://554fcacdfef7.ngrok-free.app/api/mpesa/callback',
};

// Validate environment variables AND fallback if missing
const loadMpesaConfig = () => {
    const missing = required.filter((key) => !process.env[key]);

    let config = {};

    if (missing.length > 0) {
        console.warn(
            `⚠️ Missing MPESA environment variables: ${missing.join(', ')}. ` +
            `Using fallback sandbox configuration.`
        );

        // Use fallback
        config = {
            consumerKey: fallbackConfig.MPESA_CONSUMER_KEY,
            consumerSecret: fallbackConfig.MPESA_CONSUMER_SECRET,
            passkey: fallbackConfig.MPESA_PASSKEY,
            shortCode: fallbackConfig.MPESA_SHORTCODE,
            callbackURL: fallbackConfig.MPESA_CALLBACK_URL,
            environment: fallbackConfig.MPESA_ENVIRONMENT,
        };
    } else {
        // Use environment values
        config = {
            consumerKey: process.env.MPESA_CONSUMER_KEY,
            consumerSecret: process.env.MPESA_CONSUMER_SECRET,
            passkey: process.env.MPESA_PASSKEY,
            shortCode: process.env.MPESA_SHORTCODE,
            callbackURL: process.env.MPESA_CALLBACK_URL,
            environment: process.env.MPESA_ENVIRONMENT || 'sandbox',
        };
    }

    return config;
};

module.exports = loadMpesaConfig();



// // config/mpesaConfig.js
// require('dotenv').config();

// /**
//  * Validate environment variables
//  */
// const validateEnvVariables = () => {
//   const required = [
//     'MPESA_CONSUMER_KEY',
//     'MPESA_CONSUMER_SECRET',
//     'MPESA_PASSKEY',
//     'MPESA_SHORTCODE',
//     'MPESA_CALLBACK_URL',
//   ];

//   const missing = required.filter((key) => !process.env[key]);

//   if (missing.length > 0) {
//     throw new Error(
//       `Missing required environment variables: ${missing.join(', ')}\n` +
//       'Please check your .env file'
//     );
//   }
// };

// // Validate on import
// validateEnvVariables();

// // Export the configuration
// const mpesaConfig = {
//   consumerKey: process.env.MPESA_CONSUMER_KEY,
//   consumerSecret: process.env.MPESA_CONSUMER_SECRET,
//   passkey: process.env.MPESA_PASSKEY,
//   shortCode: process.env.MPESA_SHORTCODE,
//   callbackURL: process.env.MPESA_CALLBACK_URL,
//   environment: process.env.MPESA_ENVIRONMENT || 'sandbox',
// };

// module.exports = mpesaConfig;
