const fs = require('fs');
const path = require('path');

// Load .env manually (Passenger does not auto-load .env)
const envPath = path.join(__dirname, '.env');
if (fs.existsSync(envPath)) {
  fs.readFileSync(envPath, 'utf8').split('\n').forEach(line => {
    line = line.trim();
    if (line && !line.startsWith('#')) {
      const eqIndex = line.indexOf('=');
      if (eqIndex > 0) {
        const key = line.substring(0, eqIndex).trim();
        const value = line.substring(eqIndex + 1).trim();
        if (!process.env[key]) {
          process.env[key] = value;
        }
      }
    }
  });
}

process.env.NODE_ENV = 'production';

// Load the Express app
const app = require('./server/index.cjs');

// Passenger listens on a unix socket via 'passenger' port
if (typeof PhusionPassenger !== 'undefined') {
  PhusionPassenger.configure({ autoInstall: false });
  app.listen('passenger', () => {
    console.log('EasyGDS Operations running via Passenger');
  });
} else {
  const PORT = process.env.PORT || 3001;
  app.listen(PORT, () => {
    console.log(`EasyGDS Operations running on port ${PORT}`);
  });
}
