// PM2 Ecosystem File für TimeClock v3
// Verwendung:
//   pm2 start ecosystem.config.js
//   pm2 start ecosystem.config.js --env production
//   pm2 stop timeclock-backend
//   pm2 restart timeclock-backend
//   pm2 logs timeclock-backend
//   pm2 monit

module.exports = {
  apps: [
    {
      // Backend-API
      name: 'timeclock-backend',
      cwd: '/var/www/timeclock/backend',
      script: 'src/index.js',
      
      // Instanzen (1 = single, 0 oder 'max' = alle CPU-Kerne)
      instances: 1,
      exec_mode: 'fork', // 'fork' oder 'cluster'
      
      // Environment
      env: {
        NODE_ENV: 'development',
        PORT: 3010
      },
      env_production: {
        NODE_ENV: 'production',
        PORT: 3010
      },
      
      // Auto-Restart
      watch: false, // In Produktion false
      watch_delay: 1000,
      ignore_watch: [
        'node_modules',
        'logs',
        '*.log'
      ],
      
      // Restart-Verhalten
      autorestart: true,
      max_restarts: 10,
      min_uptime: '10s',
      restart_delay: 4000,
      
      // Limits
      max_memory_restart: '500M',
      
      // Logs
      log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
      error_file: '/var/log/timeclock/pm2-error.log',
      out_file: '/var/log/timeclock/pm2-out.log',
      log_file: '/var/log/timeclock/pm2-combined.log',
      
      // Merge Logs (alle Instanzen in eine Datei)
      merge_logs: true,
      
      // Source Maps Support
      source_map_support: false,
      
      // Graceful Shutdown
      kill_timeout: 5000,
      wait_ready: false,
      listen_timeout: 10000,
      
      // Process Management
      pid_file: '/var/run/timeclock-backend.pid',
      
      // Cron Restart (optional)
      // cron_restart: '0 2 * * *', // Täglich um 2 Uhr neustarten
      
      // Monitoring
      instance_var: 'INSTANCE_ID',
      
      // Post-Deployment-Hooks (optional)
      post_update: [
        'npm install --production',
        'echo "Backend updated"'
      ]
    }
  ],

  // Deployment-Konfiguration (optional, für pm2 deploy)
  deploy: {
    production: {
      user: 'torsten',
      host: 'stechuhr3.tsschulz.de',
      ref: 'origin/main',
      repo: 'git@github.com:IHR-USERNAME/TimeClock.git',
      path: '/var/www/timeclock',
      'pre-deploy-local': '',
      'post-deploy': 'cd backend && npm install --production && pm2 reload ecosystem.config.js --env production',
      'pre-setup': ''
    }
  }
};

