// ecosystem.config.js
const path = require('path');
const dotenv = require('dotenv');

// Load environment variables safely with error handling
const loadEnvFile = (envPath) => {
  try {
    console.log('Loading env from:', envPath);
    const result = dotenv.config({ path: envPath });
    if (result.error) {
      console.warn(`Warning: .env file not found or invalid at ${envPath}:`, result.error.message);
      return {};
    }
    console.log('Env variables loaded from', envPath, ':', Object.keys(result.parsed || {}));
    return result.parsed || {};
  } catch (error) {
    console.warn(`Warning: Error loading .env file at ${envPath}:`, error.message);
    return {};
  }
};

// Load environment variables for each server
const authEnv = loadEnvFile(path.resolve(__dirname, 'auth-server/.env'));
const aircallEnv = loadEnvFile(path.resolve(__dirname, 'aircall-server/.env'));
const klaviyoEnv = loadEnvFile(path.resolve(__dirname, 'klaviyo-server/.env'));

// Common log settings for all apps
const logSettings = {
  log_rotate: true,
  max_size: '10M',
  retain: '10',
  log_date_format: 'YYYY-MM-DD HH:mm:ss'
};

// Common app settings
const commonSettings = {
  instances: 1,
  exec_mode: 'fork',
  autorestart: true,
  watch: false,
  max_memory_restart: '1G',
  time: true,
  ...logSettings,
  ignore_watch: [
    'node_modules',
    'logs',
    '.git',
    '*.log'
  ],
  min_uptime: 5000,
  max_restarts: 5,
  restart_delay: 4000,
  listen_timeout: 50000,
  kill_timeout: 5000,
  node_args: '--max-old-space-size=1536'
};

module.exports = {
  apps: [
    {
      ...commonSettings,
      name: 'auth-server',
      script: './auth-server/index.js',
      env: {
        NODE_ENV: 'production',
        PORT: 3003,
        ...authEnv
      },
      error_file: 'auth-server/logs/pm2/err.log',
      out_file: 'auth-server/logs/pm2/out.log',
      log_file: 'auth-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        PORT: 3003
      },
      env_development: {
        NODE_ENV: 'development',
        PORT: 3003
      }
    },
    {
      ...commonSettings,
      name: 'aircall-server',
      script: './aircall-server/server.js',
      env: {
        NODE_ENV: 'production',
        AIRCALL_PORT: 3002,
        ...aircallEnv
      },
      error_file: 'aircall-server/logs/pm2/err.log',
      out_file: 'aircall-server/logs/pm2/out.log',
      log_file: 'aircall-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        AIRCALL_PORT: 3002
      }
    },
    {
      ...commonSettings,
      name: 'klaviyo-server',
      script: './klaviyo-server/server.js',
      env: {
        NODE_ENV: 'production',
        KLAVIYO_PORT: 3004,
        ...klaviyoEnv
      },
      error_file: 'klaviyo-server/logs/pm2/err.log',
      out_file: 'klaviyo-server/logs/pm2/out.log',
      log_file: 'klaviyo-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        KLAVIYO_PORT: 3004
      }
    }
  ]
};
