// PM2 process definitions for CertsNexus — backend API + frontend SPA.
//
// First-time setup on the server:
//   npm i -g pm2
//
//   # Backend: install deps, generate client, sync DB schema + seed
//   cd Backend && npm ci && npx prisma generate && npx prisma db push && npm run seed && cd ..
//
//   # Frontend: install deps and build (VITE_API_URL=/api so it uses the nginx proxy)
//   cd Frontend && npm ci && npm run build && cd ..
//
//   # Start both processes and keep them alive across reboots
//   pm2 start ecosystem.config.cjs
//   pm2 save
//   pm2 startup    # run the command it prints, once
//
// Useful: pm2 status | pm2 logs | pm2 restart certsnexus-api | pm2 reload all
//
// After pulling new code:
//   cd Backend && npm ci && npx prisma db push && cd ..      # if backend/schema changed
//   cd Frontend && npm ci && npm run build && cd ..          # if frontend changed
//   pm2 reload all

module.exports = {
  apps: [
    {
      name: 'certsnexus-api',
      cwd: './Backend',
      script: 'src/server.js',
      instances: 1,
      exec_mode: 'fork',
      // PORT/secrets come from Backend/.env (loaded by dotenv). NODE_ENV here
      // flips the app into production mode (secure cookies, no morgan logging).
      env: {
        NODE_ENV: 'development',
        PORT: 5050,
      },
      max_memory_restart: '500M',
      time: true, // prefix logs with timestamps
    },
    {
      // PM2's built-in static file server (no extra dependency). Serves the Vite
      // build with SPA fallback so client-side routes resolve to index.html.
      name: 'certsnexus-web',
      script: 'serve',
      env: {
        PM2_SERVE_PATH: './Frontend/dist',
        PM2_SERVE_PORT: 4173,
        PM2_SERVE_SPA: 'true',
        PM2_SERVE_HOMEPAGE: '/index.html',
      },
    },
  ],
};
