import db from "../src/models/index.js";
import TransactionController from "../src/controllers/transactionController.js";
import WebhookController from "../src/controllers/webhookController.js";
import { v4 as uuidv4 } from "uuid";

async function verifyMerchantOversight() {
    console.log("🧪 Starting Merchant Webhook Oversight Verification...");

    try {
        // 1. Setup a test merchant and customer
        const mId = uuidv4();
        const cId = uuidv4();
        const accNo = `TESTACC-${Date.now()}`;

        const merchant = await db.Merchant.create({
            id: mId,
            email: `merch-${Date.now()}@test.com`,
            businessName: "Test Merchant Oversight",
            password: "hashed",
            webhookUrl: "https://example-merchant.com/webhook",
            merchantAccountNumber: `M-${accNo}`
        });


        const customer = await db.Customer.create({
            id: cId,
            merchantId: mId,
            fullName: "Test Customer",
            email: `cust-${Date.now()}@test.com`,
            accountNumber: accNo,
            balance: 0
        });

        console.log(`✅ Setup Merchant (${mId}) and Customer (${accNo})`);

        // 2. Simulate an INCOMING webhook (9PSB payload)
        const sessionId = `SESS-${uuidv4().slice(0,8)}`;
        const payload = {
            code: "00",
            transaction: { sessionid: sessionId, date: new Date().toISOString() },
            customer: { account: { number: accNo, name: "Test Customer" } },
            order: { amount: "1000", currency: "NGN" }
        };

        const incomingLog = await db.WebhookLog.create({
            payload,
            status: "received"
        });

        console.log(`✅ Created incoming log: ${incomingLog.id}`);

        // 3. Test RETRY Case B (Not processed yet)
        console.log("🔄 Testing Case B: Retry non-processed webhook...");
        // Mocking req object for controller
        const req = {
            merchant: { id: mId },
            params: { id: incomingLog.id }
        };
        const res = {
            status: (code) => ({ json: (data) => console.log(`  [RES ${code}]`, data) })
        };

        await WebhookController.retryIncomingWebhook(req, res);

        // Verify balance
        await customer.reload();
        console.log(`  Customer Balance: ${customer.balance} (Expected 1000)`);

        // 4. Test RETRY Case A (Already processed)
        console.log("🔄 Testing Case A: Retry ALREADY processed webhook...");
        await WebhookController.retryIncomingWebhook(req, res);

        // 5. Verify Outgoing Logs
        console.log("🔎 Verifying Outgoing Logs...");
        const outgoingReq = {
            merchant: { id: mId },
            query: {}
        };
        await WebhookController.getOutgoingLogs(outgoingReq, res);

        console.log("🧪 Verification script completed.");
    } catch (error) {
        console.error("❌ Verification failed:", error);
    } finally {
        process.exit(0);
    }
}

verifyMerchantOversight();
