const express = require("express");
const router = express.Router();
const Setting = require("../models/setting.model");
const { encrypt, decrypt } = require("../helper/encryptAndDcrypt");
const { uploadToStorage } = require("../utils/uploadToStorage");
const { isAuthenticated, allowRoles } = require("../middlewares/authenticate");
const { uploadSettingsDocs } = require("../middlewares/multer.middleware");
const { updateSettingValidation } = require("../validation/setting.validation");
const { checkPermission } = require("../middlewares/checkPermission");

// Helper paths for sensitive keys
const sensitivePaths = [
    "pushNotification.firebaseServerKey",
    "googleMap.httpRestrictionKey",
    "googleMap.ipRestrictionKey",
    "googleMap.unrestrictedKey",
    "paymentGateways.razorpay.secretKey",
    "paymentGateways.stripe.secretKey",
    "paymentGateways.paypal.clientSecret",
    "sms.authToken",
    "email.pass",
];

// Helper to mask/decrypt sensitive fields
const processSensitiveFields = (obj, action) => {
    sensitivePaths.forEach((path) => {
        const keys = path.split(".");
        let current = obj;
        for (let i = 0; i < keys.length - 1; i++) {
            if (current && current[keys[i]]) current = current[keys[i]];
            else { current = null; break; }
        }
        const lastKey = keys[keys.length - 1];
        if (current && current[lastKey]) {
            if (action === "decrypt") current[lastKey] = decrypt(current[lastKey]);
            else if (action === "mask") {
                if (current[lastKey].includes(":")) current[lastKey] = "********";
            }
        }
    });
};

// Public route to get settings (Logo, Hero Section, etc.)
router.get("/public", async (req, res) => {
    try {
        const settings = await Setting.getSettings();
        const { design, general, seo, socialLogin } = settings;

        // Return only necessary public info
        return res.status(200).json({
            success: true,
            data: {
                design,
                general,
                seo,
                socialLogin: {
                    facebook: { enabled: socialLogin?.facebook?.enabled, appId: socialLogin?.facebook?.appId },
                    google: { enabled: socialLogin?.google?.enabled, clientId: socialLogin?.google?.clientId }
                }
            }
        });
    } catch (error) {
        return res.status(500).json({ success: false, message: error.message });
    }
});

// ============================================================================
// PUBLIC ENDPOINT: Global Language Setting
// This is the PRIMARY endpoint all frontends should use to get the system language.
// No authentication required - panels fetch this on app load.
// Response format: { success: true, data: { language: "en" | "hi" | ... } }
// ============================================================================
router.get("/language", async (req, res) => {
    /*  #swagger.tags = ['Settings']
        #swagger.description = 'Get global system language (public, no auth required). All panels should fetch this on app load.'
        #swagger.responses[200] = {
            description: 'Global language setting',
            schema: {
                success: true,
                data: {
                    language: 'en'
                }
            }
        }
    */
    try {
        const settings = await Setting.getSettings();
        const language = settings?.language?.defaultLanguage || "en";

        return res.status(200).json({
            success: true,
            data: {
                language
            }
        });
    } catch (error) {
        console.error("Error fetching language setting:", error);
        return res.status(500).json({
            success: false,
            message: "Failed to fetch language setting",
            data: { language: "en" } // Fallback to English on error
        });
    }
});

// All routes below are protected and for super-admin only
router.use(isAuthenticated, allowRoles("super-admin", "staff"), checkPermission("manage_settings"));

const SettingController = require("../controllers/setting.controller");

/**
 * @route   GET /api/v1/settings
 */
router.get("/", SettingController.getSettings);

/**
 * @route   PUT /api/v1/settings
 */
router.put("/", uploadSettingsDocs, SettingController.updateSettings);

// ============================================================================
// SUPER ADMIN ONLY: Update Global Language Setting
// This is the ONLY way to change the system-wide language.
// Only Super Admin can access this endpoint (protected by middleware above).
// ============================================================================

// Allowed language codes (expand as needed)
const ALLOWED_LANGUAGES = ["en", "hi", "fr", "de", "ar", "es"];

router.put("/language", async (req, res) => {
    /*  #swagger.tags = ['Settings']
        #swagger.description = 'Update global system language (Super Admin only). Changes apply to all panels on next load/refresh.'
        #swagger.security = [{ "bearerAuth": [] }]
        #swagger.parameters['body'] = {
            in: 'body',
            required: true,
            schema: {
                $language: 'hi'
            }
        }
        #swagger.responses[200] = {
            description: 'Language updated successfully',
            schema: {
                success: true,
                message: 'System language updated to Hindi',
                data: {
                    language: 'hi',
                    previousLanguage: 'en'
                }
            }
        }
        #swagger.responses[400] = {
            description: 'Invalid language code'
        }
        #swagger.responses[403] = {
            description: 'Access denied - Super Admin only'
        }
    */
    try {
        const { language } = req.body;

        // Validate language parameter
        if (!language) {
            return res.status(400).json({
                success: false,
                message: "Language is required",
                allowedLanguages: ALLOWED_LANGUAGES
            });
        }

        // Validate language is in allowed list
        if (!ALLOWED_LANGUAGES.includes(language)) {
            return res.status(400).json({
                success: false,
                message: `Invalid language code: ${language}`,
                allowedLanguages: ALLOWED_LANGUAGES
            });
        }

        // Get current settings
        const settings = await Setting.getSettings();
        const previousLanguage = settings?.language?.defaultLanguage || "en";

        // Check if language is actually changing
        if (previousLanguage === language) {
            return res.status(200).json({
                success: true,
                message: `System language is already set to ${language}`,
                data: {
                    language,
                    previousLanguage
                }
            });
        }

        // Update only the language field
        const updatedSettings = await Setting.findOneAndUpdate(
            { _id: settings._id },
            {
                $set: {
                    "language.defaultLanguage": language,
                    // Ensure the new language is in available languages
                    "language.availableLanguages": [...new Set([...settings.language.availableLanguages, language])]
                }
            },
            { new: true, runValidators: true }
        );

        // Log the change (for audit trail)
        console.log(`[LANGUAGE CHANGE] Super Admin ${req.user?.email || req.user?._id} changed language from ${previousLanguage} to ${language}`);

        return res.status(200).json({
            success: true,
            message: `System language updated to ${language}`,
            data: {
                language: updatedSettings.language.defaultLanguage,
                previousLanguage
            }
        });

    } catch (error) {
        console.error("Error updating language setting:", error);
        return res.status(500).json({
            success: false,
            message: error.message || "Failed to update language setting"
        });
    }
});

module.exports = router;
