const axios = require('axios');

/**
 * Send OneSignal Push Notification to all users
 * @param {string} title - Notification title
 * @param {string} message - Notification message/content
 * @param {Object} data - Additional data payload (optional)
 * @returns {Object} - Response object
 */
const sendOneSignalNotification = async (title, message, data = {}) => {
    try {
        console.log("🚀 Sending OneSignal Notification:", { title, message, data });

        // OneSignal credentials (move these to environment variables in production)
        const appId = process.env.ONESIGNAL_APP_ID || "";
        const apiKey = process.env.ONESIGNAL_API_KEY || "";

        if (!appId || !apiKey) {
            console.warn("⚠️ OneSignal credentials missing.");
            return {
                success: false,
                error: "OneSignal credentials missing",
                message: "Notification skipped - credentials not configured"
            };
        }

        // Create OneSignal payload
        const payload = {
            app_id: appId,
            headings: { en: title || "Notification" },
            contents: { en: message || "New update available" },
            included_segments: ["All"], // Send to all subscribed users
            data: data,
            // Additional options:
            // url: data.url || "", // Deep linking
            // chrome_web_icon: "https://example.com/icon.png", // Web icon
            // android_accent_color: "FF0000", // Android accent color
            // ios_badgeType: "Increase", // iOS badge type
            // ios_badgeCount: 1 // iOS badge count
        };

        console.log("📤 OneSignal Payload:", JSON.stringify(payload, null, 2));

        // Send notification to OneSignal API
        const response = await axios.post(
            "https://api.onesignal.com/notifications",
            payload,
            {
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Basic ${apiKey}`,
                },
                timeout: 15000 // 15 second timeout
            }
        );

        console.log("✅ OneSignal Notification Sent Successfully:", {
            notificationId: response.data.id,
            recipients: response.data.recipients,
            errors: response.data.errors
        });

        return {
            success: true,
            notificationId: response.data.id,
            recipients: response.data.recipients,
            data: response.data
        };

    } catch (error) {
        console.error("🔴 OneSignal Notification Error:", {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status
        });

        return {
            success: false,
            error: error.message,
            response: error.response?.data,
            status: error.response?.status
        };
    }
};

/**
 * Send Game Result Notification
 * @param {string} gameName - Name of the game
 * @param {string} result - Game result (e.g., "123-6")
 * @param {string} resultType - Type of result ('open', 'close', 'jodi')
 * @param {string} gameId - Game database ID
 * @returns {Object} - Response object
 */
const sendGameResultNotification = async (gameName, result, resultType = 'open', gameId = null) => {
    const title = `${gameName} - ${resultType.charAt(0).toUpperCase() + resultType.slice(1)} Result Declared`;
    const message = `${resultType.charAt(0).toUpperCase() + resultType.slice(1)} result declared: ${result}`;

    const data = {
        gameId: gameId,
        result: result,
        type: `${resultType}_result`,
        timestamp: new Date().toISOString(),
        action: 'game_result'
    };

    return await sendOneSignalNotification(title, message, data);
};

/**
 * Send Maintenance Notification
 * @param {string} message - Maintenance message
 * @param {string} duration - Duration of maintenance
 * @returns {Object} - Response object
 */
const sendMaintenanceNotification = async (message, duration = '') => {
    const title = 'Maintenance Alert';
    const fullMessage = duration ? `${message} (Duration: ${duration})` : message;

    const data = {
        type: 'maintenance',
        action: 'maintenance_alert',
        timestamp: new Date().toISOString()
    };

    return await sendOneSignalNotification(title, fullMessage, data);
};

/**
 * Send Bonus Notification
 * @param {string} message - Bonus message
 * @param {number} amount - Bonus amount
 * @returns {Object} - Response object
 */
const sendBonusNotification = async (message, amount = null) => {
    const title = amount ? `Bonus Received: ₹${amount}` : 'Bonus Received';
    const fullMessage = amount ? `${message} - ₹${amount}` : message;

    const data = {
        type: 'bonus',
        action: 'bonus_received',
        amount: amount,
        timestamp: new Date().toISOString()
    };

    return await sendOneSignalNotification(title, fullMessage, data);
};

module.exports = {
    sendOneSignalNotification,
    sendGameResultNotification,
    sendMaintenanceNotification,
    sendBonusNotification
};