import { reconcilePendingPayouts } from "../services/cronService.js";

/**
 * Standalone Payout Reconciliation Worker
 * Designed to be run by PM2 cron_restart as a SINGLE dedicated process.
 *
 * This must NOT be scheduled from inside server.js. server.js runs in PM2 cluster mode with
 * multiple instances in production — a setInterval there would run once per cluster worker,
 * all in parallel, all racing to resolve the same pending payouts at the same moment. Running
 * it here instead, as its own single-instance PM2 app, guarantees it only ever runs once at a
 * time, system-wide, no matter how many cluster workers the main app has.
 */
async function runPayoutReconciliation() {
    console.log("🔄 [WORKER] Starting Payout Reconciliation...");

    try {
        await reconcilePendingPayouts();
        console.log("✅ [WORKER] Payout reconciliation complete.");
    } catch (error) {
        console.error("❌ [WORKER] Critical error in Payout Reconciliation Worker:", error);
    } finally {
        process.exit(0);
    }
}

// Run the worker
runPayoutReconciliation();
