import db from "../src/models/index.js";
import WebhookService from "../src/services/webhookService.js";
import { v4 as uuidv4 } from "uuid";

async function verifyWebhookSystem() {
    console.log("🧪 Starting Webhook System Verification...");

    try {
        // 1. Setup a test merchant
        const testMerchant = await db.Merchant.create({
            id: uuidv4(),
            email: `test-${Date.now()}@example.com`,
            businessName: "Test Merchant Webhook",
            password: "dummy",
            webhookUrl: "http://invalid-url-that-will-fail.com/webhook",
            status: "active"
        });

        console.log(`✅ Created test merchant: ${testMerchant.id}`);

        // 2. Trigger a notification
        console.log("📡 Triggering initial notification...");
        const result = await WebhookService.notifyMerchant(
            testMerchant.id, 
            "TEST_EVENT", 
            { foo: "bar" }
        );

        console.log(`Initial result (should be false due to invalid URL): ${result}`);

        // 3. Verify Log creation
        const log = await db.MerchantWebhookLog.findOne({
            where: { merchantId: testMerchant.id, event: "TEST_EVENT" },
            order: [['createdAt', 'DESC']]
        });

        if (log) {
            console.log(`✅ Log created. Status: ${log.status}, Attempts: ${log.attempts}`);
            if (log.status === 'failed' && log.attempts > 1) {
                console.log("✅ Initial local retries worked (attempts > 1).");
            } else {
                console.log("❌ Initial retries logic might be skipped or failed.");
            }
        } else {
            console.log("❌ Log not found!");
        }

        // 4. Cleanup (optional, but good for cleanliness)
        // await testMerchant.destroy();
        
        console.log("🧪 Verification script completed.");
    } catch (error) {
        console.error("❌ Verification failed:", error);
    } finally {
        process.exit(0);
    }
}

verifyWebhookSystem();
