import db from "../models/index.js";
import WebhookService from "../services/webhookService.js";
import { Op } from "sequelize";

const { MerchantWebhookLog } = db;

/**
 * Robust Webhook Retry Worker
 * This script scans for failed or pending merchant webhooks and retries them.
 */
async function runRetryWorker() {
    console.log("🔄 Starting Webhook Retry Worker...");

    try {
        // Find webhooks that are failed or pending and have not exceeded max attempts
        // Pending: created more than 5 minutes ago (to allow the initial flow to finish)
        // Failed: any failed one with < 10 attempts
        const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
        
        const webhooksToRetry = await MerchantWebhookLog.findAll({
            where: {
                [Op.or]: [
                    { status: "failed", attempts: { [Op.lt]: 10 } },
                    { status: "pending", createdAt: { [Op.lt]: fiveMinutesAgo }, attempts: { [Op.lt]: 10 } }
                ]
            },
            limit: 50 // process in batches
        });

        console.log(`🔎 Found ${webhooksToRetry.length} webhooks to retry.`);

        for (const log of webhooksToRetry) {
            try {
                console.log(`🔁 Retrying log ${log.id} (Event: ${log.event}, Attempts: ${log.attempts})`);
                await WebhookService.executeDelivery(log);
            } catch (err) {
                console.error(`❌ Failed to retry log ${log.id}:`, err.message);
            }
        }

        console.log("✅ Retry Worker finished cycle.");
    } catch (error) {
        console.error("❌ Critical Error in Retry Worker:", error);
    } finally {
        // If run manually as a script, we might want to exit. 
        // If run via PM2, we can just let it finish.
        process.exit(0);
    }
}

// Run the worker
runRetryWorker();
