const db = require('../db');

exports.getPublicSettings = async (req, res) => {
    try {
        // Create placeholders with defaults
        const settings = {
            default_threat_map: 'https://livethreatmap.radware.com',
            // Tier pricing defaults
            tier_small_price: '17.99',
            tier_medium_price: '14.99',
            tier_large_price: '12.99'
        };

        // Use explicit IN clause with constants to avoid mysql2 array binding issues
        const result = await db.query(
            `SELECT \`key\`, value FROM system_settings WHERE \`key\` IN (
                'default_threat_map',
                'plan_free_name', 'free_tier_limit',
                'plan_monthly_name', 'stripe_price_original_monthly', 'discount_monthly_percent', 'stripe_price_display_monthly',
                'plan_yearly_name', 'stripe_price_original_yearly', 'discount_yearly_percent', 'stripe_price_display_yearly',
                'tier_small_price', 'tier_medium_price', 'tier_large_price',
                'tier_small_stripe_id', 'tier_medium_stripe_id', 'tier_large_stripe_id',
                'google_analytics_id',
                'banner_enabled', 'banner_message', 'maintenance_mode', 'maintenance_message'
            )`
        );

        result.rows.forEach(row => {
            let val = row.value;
            try {
                if (typeof val === 'string' && val.startsWith('"')) {
                    val = JSON.parse(val);
                }
            } catch (e) {
                // ignore
            }
            settings[row.key] = val;
        });

        // Attach SEO metadata overrides
        try {
            const seoResult = await db.query('SELECT * FROM seo_metadata');
            const seoOverrides = {};
            if (seoResult.rows) {
                seoResult.rows.forEach(row => {
                    seoOverrides[row.route] = row;
                });
            }
            settings.seoOverrides = seoOverrides;
        } catch (e) {
            console.error('Error fetching SEO metadata for public settings:', e);
            settings.seoOverrides = {};
        }

        res.json(settings);
    } catch (error) {
        console.error('Error fetching public settings:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getSettings = async (req, res) => {
    try {
        // SECURITY FIX: Only admins should be able to fetch all settings
        if (req.user.role !== 'admin') {
            return res.status(403).json({ message: 'Access denied. Administrator privileges required.' });
        }

        const { category } = req.query;
        let query = 'SELECT `key`, value, category FROM system_settings';
        let params = [];

        if (category) {
            query += ' WHERE category = ?';
            params.push(category);
        }

        const result = await db.query(query, params);
        const settings = {};

        // Keys that contain sensitive data and should be masked
        const SENSITIVE_KEYS = ['ai_api_key', 'smtp_pass', 'google_client_secret', 'linkedin_client_secret', 'stripe_secret_key'];

        result.rows.forEach(row => {
            let val = row.value;
            try {
                if (typeof val === 'string' && (val.startsWith('{') || val.startsWith('['))) {
                    val = JSON.parse(row.value);
                }
            } catch (e) {
                // Keep as string if not valid JSON
            }

            // Mask sensitive values - only show last 4 characters
            if (SENSITIVE_KEYS.includes(row.key) && typeof val === 'string' && val.length > 4) {
                val = '••••••••' + val.slice(-4);
            }

            settings[row.key] = val;
        });

        res.json(settings);
    } catch (error) {
        console.error('Error fetching settings:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.updateSettings = async (req, res) => {
    try {
        // SECURITY FIX: Only admins should be able to update settings
        if (req.user.role !== 'admin') {
            return res.status(403).json({ message: 'Access denied. Administrator privileges required.' });
        }

        const { category, settings } = req.body;

        if (!settings || typeof settings !== 'object') {
            return res.status(400).json({ message: 'Invalid settings data' });
        }

        const connection = await db.pool.getConnection();
        try {
            await connection.beginTransaction();

            // Keys that contain sensitive data
            const SENSITIVE_KEYS = ['ai_api_key', 'smtp_pass', 'google_client_secret', 'linkedin_client_secret', 'stripe_secret_key'];

            for (const [key, value] of Object.entries(settings)) {
                // Skip masked values to prevent overwriting real secrets with the mask
                if (SENSITIVE_KEYS.includes(key) && typeof value === 'string' && value.startsWith('••••••••')) {
                    continue; // Don't overwrite — user didn't change this field
                }

                // Convert value to JSON string if it's an object/array, else use raw value
                const valStr = (typeof value === 'object') ? JSON.stringify(value) : value;

                await connection.query(
                    "INSERT INTO system_settings (`key`, value, category, updated_at) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE value = ?, updated_at = NOW(), category = COALESCE(?, category)",
                    [key, valStr, category || 'general', valStr, category]
                );
            }

            await connection.commit();
            res.json({ message: 'Settings updated successfully' });
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    } catch (error) {
        console.error('Error updating settings:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};
