// =============================================================================
// PM2 ecosystem for Vihar Sewa on kreonAI5.
// Runs as the `vihar` OS user (not root). aaPanel uses /etc/init.d/, but PM2
// is invoked via `sudo -u vihar pm2 ...` from a startup script.
//
// Ports (matching kreonAI5 monorepo convention):
//   3001 = Next.js web (frontend)
//   4001 = NestJS API (backend)
//
// Usage:
//   sudo -u vihar pm2 start ecosystem.config.js
//   sudo -u vihar pm2 save
//   sudo pm2 startup       # registers PM2 with systemd
// =============================================================================

module.exports = {
  apps: [
    {
      name: 'vihar-web',
      cwd: '/www/wwwroot/vihar/apps/web',
      script: 'node_modules/next/dist/bin/next',
      args: 'start -p 3001',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '500M',
      env: {
        NODE_ENV: 'production',
        PORT: '3001',
      },
      env_file: '/www/wwwroot/vihar/.env',
      error_file: '/var/log/vihar/web-error.log',
      out_file: '/var/log/vihar/web-out.log',
      time: true,
    },
    {
      name: 'vihar-api',
      cwd: '/www/wwwroot/vihar/apps/api',
      script: 'dist/main.js',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '500M',
      env: {
        NODE_ENV: 'production',
        API_PORT: '4001',
        API_HOST: '127.0.0.1',
      },
      env_file: '/www/wwwroot/vihar/.env',
      error_file: '/var/log/vihar/api-error.log',
      out_file: '/var/log/vihar/api-out.log',
      time: true,
    },
    // Auto-close cron - calls the internal endpoint every 30 min as a safety net
    // (the API also has its own @nestjs/schedule cron; this is belt-and-braces).
    {
      name: 'vihar-cron',
      script: '/www/wwwroot/vihar/deploy/cron-auto-close.sh',
      cron_restart: '0 */6 * * *',
      autorestart: false,
      watch: false,
      env_file: '/www/wwwroot/vihar/.env',
      error_file: '/var/log/vihar/cron-error.log',
      out_file: '/var/log/vihar/cron-out.log',
      time: true,
    },
  ],
};
