/**
 * Payment Gateway Factory
 * Returns the active payment gateway instance based on settings
 */

const Setting = require('../../models/setting.model');

/**
 * Get the currently enabled payment gateway
 * @returns {Object} { gateway, gatewayName, settings }
 */
const getActiveGateway = async () => {
    const settings = await Setting.getSettingsWithDecryption();
    const gateways = settings.paymentGateways;

    if (gateways?.razorpay?.enabled) {
        const razorpayGateway = require('./razorpay.gateway');
        return {
            gateway: razorpayGateway,
            gatewayName: 'razorpay',
            config: gateways.razorpay
        };
    }

    if (gateways?.stripe?.enabled) {
        const stripeGateway = require('./stripe.gateway');
        return {
            gateway: stripeGateway,
            gatewayName: 'stripe',
            config: gateways.stripe
        };
    }

    throw { message: 'No payment gateway is enabled. Please enable a payment gateway in settings.', statusCode: 400 };
};

/**
 * Get a specific gateway by name
 * @param {String} gatewayName - 'razorpay' or 'stripe'
 * @returns {Object} { gateway, gatewayName, config }
 */
const getGatewayByName = async (gatewayName) => {
    const settings = await Setting.getSettingsWithDecryption();
    const gateways = settings.paymentGateways;

    switch (gatewayName) {
        case 'razorpay': {
            const razorpayGateway = require('./razorpay.gateway');
            return {
                gateway: razorpayGateway,
                gatewayName: 'razorpay',
                config: gateways.razorpay
            };
        }
        case 'stripe': {
            const stripeGateway = require('./stripe.gateway');
            return {
                gateway: stripeGateway,
                gatewayName: 'stripe',
                config: gateways.stripe
            };
        }
        default:
            throw { message: `Unknown payment gateway: ${gatewayName}`, statusCode: 400 };
    }
};

module.exports = {
    getActiveGateway,
    getGatewayByName
};
