const isProduction = process.argv.includes("production") || process.env.NODE_ENV === "production";

module.exports = {
  apps: [
    {
      name: "airpero-staging-saas",
      script: "src/server.js",
      instances: isProduction ? "max" : 1, // Cluster only on production
      exec_mode: isProduction ? "cluster" : "fork",
      watch: false,
      max_memory_restart: "1G",
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
      env_staging: {
        NODE_ENV: "staging",
      },
      error_file: "./logs/err.log",
      out_file: "./logs/out.log",
      log_date_format: "YYYY-MM-DD HH:mm:ss Z",
    },
    {
      name: "webhook-retry-worker",
      script: "src/scripts/webhookRetryWorker.js",
      instances: 1,
      autorestart: false, // Don't restart immediately; rely on cron
      watch: false,
      cron_restart: "*/15 * * * *", // Run every 15 minutes
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
      env_staging: {
        NODE_ENV: "staging",
      },
      error_file: "./logs/webhook-retry-err.log",
      out_file: "./logs/webhook-retry-out.log",
    },
    {
      name: "inactivity-checker",
      script: "src/scripts/inactivityWorker.js",
      instances: 1,
      autorestart: false,
      watch: false,
      cron_restart: "0 0 * * *", // Run once a day at midnight
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
      env_staging: {
        NODE_ENV: "staging",
      },
      error_file: "./logs/inactivity-err.log",
      out_file: "./logs/inactivity-out.log",
    },
    {
      name: "payout-recovery-worker",
      script: "src/scripts/recoverUnrecordedPayoutsWorker.js",
      instances: 1, // Must run once per cycle, not once per cluster worker
      autorestart: false,
      watch: false,
      cron_restart: "*/5 * * * *", // Run every 5 minutes — this recovers real, unrecorded money
      env: {
        NODE_ENV: "production",
      },
      error_file: "./logs/payout-recovery-err.log",
      out_file: "./logs/payout-recovery-out.log",
    },
    {
      name: "payout-reconciliation-worker",
      script: "src/scripts/payoutReconciliationWorker.js",
      instances: 1, // Must run once per cycle, not once per cluster worker — this was
                    // previously scheduled from inside server.js's setInterval, which ran
                    // once per cluster instance in parallel and caused duplicate refunds and
                    // duplicate merchant webhooks for the same payout.
      autorestart: false,
      watch: false,
      cron_restart: "*/10 * * * *", // Run every 10 minutes, matching the previous interval
      env: {
        NODE_ENV: "production",
      },
      error_file: "./logs/payout-reconciliation-err.log",
      out_file: "./logs/payout-reconciliation-out.log",
    },

  ],
};
