const cron = require("node-cron");
const PayoutService = require("../services/payoutService");

// Daily retry job for failed payouts (hourly job removed - payouts are now triggered immediately on completion)
const retrySchedule = "0 7 * * *"; // Retry failed payouts once daily at 7 AM

class PayoutProcessor {
  static startScheduledPayouts() {
    console.log("Starting payout retry processor...");

    const retryJob = cron.schedule(
      retrySchedule,
      async () => {
        console.log("Running failed payout retry process...");

        try {
          const results = await PayoutService.retryFailedPayouts();

          if (results.totalProcessed > 0) {
            console.log(
              `Retry batch completed: ${results.successful.length} successful, ${results.failed.length} still failed`
            );
          }
        } catch (error) {
          console.error("Error in retry payout processing:", error);
        }
      },
      {
        scheduled: false,
        timezone: "America/New_York",
      }
    );

    // Start the job
    retryJob.start();

    console.log("Payout processor jobs scheduled:");
    console.log("- Daily retry processing: " + retrySchedule);

    return {
      retryJob,

      stop() {
        retryJob.stop();
        console.log("Payout processor jobs stopped");
      },

      getStatus() {
        return {
          retryJobRunning: retryJob.getStatus() === "scheduled",
        };
      },
    };
  }
}

module.exports = PayoutProcessor;
