const SettingService = require("../services/setting.service");
const { updateSettingValidation } = require("../validation/setting.validation");

/**
 * Get settings (masked).
 */
const getSettings = async (req, res) => {
    try {
        const settings = await SettingService.getSettings(false);
        return res.status(200).json({
            success: true,
            message: "Settings retrieved successfully",
            data: settings,
        });
    } catch (error) {
        console.error("Error in getSettings controller:", error);
        return res.status(500).json({
            success: false,
            message: error.message || "Internal Server Error",
        });
    }
};

/**
 * Update settings.
 */
const updateSettings = async (req, res) => {
    console.log("Data: ", req.body);
    try {
        let data = req.body;

        if (!data || Object.keys(data).length === 0) {
            return res.status(400).json({
                success: false,
                message: "No data provided",
            });
        }
        // Handle multipart/form-data parsing for nested JSON strings
        Object.keys(data).forEach((key) => {
            if (typeof data[key] === "string") {
                try {
                    data[key] = JSON.parse(data[key]);
                } catch (e) {
                    // Not a JSON string, keep as is
                }
            }
        });

        // Transform SMS/WhatsApp data if present (from Frontend Settings.jsx)
        if (data.sms) {
            console.log("Transforming SMS data to Messaging structure:", data.sms);

            data.messaging = {
                sms: {
                    enabled: true,
                    provider: data.sms.provider || "Twilio",
                    twilio: {
                        accountSid: data.sms.sid || "",
                        authToken: data.sms.authToken || "",
                        fromNumber: data.sms.fromNumber || "",
                        apiUrl: data.sms.twilioSmsApiUrl || "https://api.twilio.com/2010-04-01/Accounts"
                    },
                    fast2sms: {
                        apiKey: data.sms.fast2smsApiKey || "",
                        senderId: data.sms.fast2smsSenderId || "",
                        apiUrl: data.sms.fast2smsSmsApiUrl || "https://www.fast2sms.com/dev/bulkV2"
                    }
                },
                whatsapp: {
                    enabled: true,
                    provider: data.sms.whatsappProvider || "Twilio",
                    twilio: {
                        accountSid: data.sms.twilioWhatsappSid || data.sms.sid || "",
                        authToken: data.sms.twilioWhatsappAuthToken || data.sms.authToken || "",
                        fromNumber: data.sms.twilioWhatsappNumber || "",
                        apiUrl: data.sms.twilioWhatsappApiUrl || "https://api.twilio.com/2010-04-01/Accounts"
                    },
                    fast2sms: {
                        apiKey: data.sms.fast2smsWhatsappApiKey || data.sms.fast2smsApiKey || "",
                        apiUrl: data.sms.fast2smsWhatsappApiUrl || "https://www.fast2sms.com/dev/whatsapp"
                    }
                }
            };

            // Remove the old sms key to avoid validation errors or clutter
            delete data.sms;
        }

        // Validation
        const { error } = updateSettingValidation(data);
        if (error) {
            return res.status(400).json({
                success: false,
                message: "Validation Error",
                errors: error.details.map((d) => d.message),
            });
        }

        const updatedSettings = await SettingService.updateSettings(data, req.files);

        return res.status(200).json({
            success: true,
            message: "Settings updated successfully",
            data: updatedSettings,
        });
    } catch (error) {
        console.error("Error in updateSettings controller:", error);
        return res.status(500).json({
            success: false,
            message: error.message || "Internal Server Error",
        });
    }
};

module.exports = {
    getSettings,
    updateSettings,
};
