/**
 * PM2 ecosystem for the resolution pollers.
 *
 *   cd poller && pm2 start ecosystem.config.js
 *
 * Each sport runs in its own process so a runaway request loop on one
 * upstream can't starve the others. cwd is the repo root so `../src/*`
 * relative imports inside poller.js resolve correctly under PM2.
 */

const path = require('path');
const ROOT = path.resolve(__dirname, '..');

const baseEnv = {
  POLL_INTERVAL: '60000',
  BUFFER_MS: '30000',
};

function poller(sport, env = {}) {
  return {
    name: `poller-${sport}`,
    script: path.join(__dirname, 'poller.js'),
    cwd: ROOT,
    env: { ...baseEnv, ...env, SPORT: sport },
    max_memory_restart: '256M',
    log_type: 'json',
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
    autorestart: true,
    // Restart up to 10× per minute if the process keeps crashing — gives
    // a transient ESPN outage time to clear before pm2 backs off.
    max_restarts: 10,
    min_uptime: '30s',
  };
}

// Soccer poller (Session 7j) — own script because the data sources
// (worldcup2026 OSS + football-data.org) and cache shape (per-team
// next/last match pointers) differ from the box-score resolution path.
// SOCCER_LEAGUES env controls which competitions get polled; default 'WC'.
function soccerPoller(env = {}) {
  return {
    name: 'poller-soccer',
    script: require('path').join(__dirname, 'soccer.js'),
    cwd: ROOT,
    env: {
      ...baseEnv,
      ...env,
      SOCCER_LEAGUES: env.SOCCER_LEAGUES || process.env.SOCCER_LEAGUES || 'WC',
    },
    max_memory_restart: '256M',
    log_type: 'json',
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
    autorestart: true,
    max_restarts: 10,
    min_uptime: '30s',
  };
}

module.exports = {
  apps: [
    poller('nba'),
    poller('wnba'),
    poller('mlb'),
    soccerPoller(),
    // Uncomment when in-season — keeping commented to save memory off-season.
    // poller('nfl'),
    // poller('ncaafb'),
    // poller('nhl'),
    // poller('ncaab'),
  ],
};
