/**
 * Webhook Service
 * Handles triggering and managing webhooks
 */

const axios = require('axios');
const Webhook = require('../models/webhook.model');

/**
 * Trigger webhooks for a specific event
 * @param {String} eventType - The type of event (e.g., 'booking_confirmation')
 * @param {Object} data - The payload to send
 */
exports.triggerWebhook = async (eventType, data) => {
    try {
        // Find all active webhooks for this event
        const webhooks = await Webhook.find({ eventType, isActive: true });

        if (!webhooks || webhooks.length === 0) {
            return { success: true, message: 'No active webhooks for this event' };
        }

        console.log(`Triggering ${webhooks.length} webhooks for event: ${eventType}`);

        // Trigger each webhook asynchronously
        const triggerPromises = webhooks.map(async (webhook) => {
            try {
                const payload = {
                    event: eventType,
                    timestamp: new Date().toISOString(),
                    data: data,
                };

                // Add signature if secret is configured (optional enhancement)
                const headers = {
                    'Content-Type': 'application/json',
                    'X-Webhook-Event': eventType,
                };

                const response = await axios.post(webhook.url, payload, {
                    headers,
                    timeout: 10000 // 10 second timeout
                });

                // Update last triggered and reset failure count
                await Webhook.findByIdAndUpdate(webhook._id, {
                    lastTriggeredAt: new Date(),
                    failureCount: 0
                });

                return { url: webhook.url, success: true };

            } catch (error) {
                console.error(`Webhook failed for ${webhook.url}:`, error.message);

                // Increment failure count
                await Webhook.findByIdAndUpdate(webhook._id, {
                    $inc: { failureCount: 1 }
                });

                return { url: webhook.url, success: false, error: error.message };
            }
        });

        // Use setImmediate to allow the main process to continue without waiting for all webhooks
        setImmediate(async () => {
            const results = await Promise.allSettled(triggerPromises);
            console.log(`Webhook results for ${eventType}:`, results.map(r => r.status === 'fulfilled' ? r.value : r.reason));
        });

        return { success: true, count: webhooks.length };

    } catch (error) {
        console.error('Error in triggerWebhook:', error);
        return { success: false, error: error.message };
    }
};

/**
 * CRUD Operations for Controller
 */
exports.createWebhook = async (webhookData) => {
    return await Webhook.create(webhookData);
};

exports.getAllWebhooks = async () => {
    return await Webhook.find().sort({ createdAt: -1 });
};

exports.deleteWebhook = async (id) => {
    return await Webhook.findByIdAndDelete(id);
};

exports.updateWebhook = async (id, updateData) => {
    return await Webhook.findByIdAndUpdate(id, updateData, { new: true });
};
