// 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, 'dashboard/auth-server/.env'));
const aircallEnv = loadEnvFile(path.resolve(__dirname, 'dashboard/aircall-server/.env'));
const klaviyoEnv = loadEnvFile(path.resolve(__dirname, 'dashboard/klaviyo-server/.env'));
const metaEnv = loadEnvFile(path.resolve(__dirname, 'dashboard/meta-server/.env'));
const googleAnalyticsEnv = require('dotenv').config({ 
  path: path.resolve(__dirname, 'dashboard/google-server/.env') 
}).parsed || {};
const typeformEnv = loadEnvFile(path.resolve(__dirname, 'dashboard/typeform-server/.env'));
const inventoryEnv = loadEnvFile(path.resolve(__dirname, 'inventory/.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: './dashboard/auth-server/index.js',
      env: {
        NODE_ENV: 'production',
        PORT: 3003,
        ...authEnv
      },
      error_file: 'dashboard/auth-server/logs/pm2/err.log',
      out_file: 'dashboard/auth-server/logs/pm2/out.log',
      log_file: 'dashboard/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: './dashboard/aircall-server/server.js',
      env: {
        NODE_ENV: 'production',
        AIRCALL_PORT: 3002,
        ...aircallEnv
      },
      error_file: 'dashboard/aircall-server/logs/pm2/err.log',
      out_file: 'dashboard/aircall-server/logs/pm2/out.log',
      log_file: 'dashboard/aircall-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        AIRCALL_PORT: 3002
      }
    },
    {
      ...commonSettings,
      name: 'klaviyo-server',
      script: './dashboard/klaviyo-server/server.js',
      env: {
        NODE_ENV: 'production',
        KLAVIYO_PORT: 3004,
        ...klaviyoEnv
      },
      error_file: 'dashboard/klaviyo-server/logs/pm2/err.log',
      out_file: 'dashboard/klaviyo-server/logs/pm2/out.log',
      log_file: 'dashboard/klaviyo-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        KLAVIYO_PORT: 3004
      }
    },
    {
      ...commonSettings,
      name: 'meta-server',
      script: './dashboard/meta-server/server.js',
      env: {
        NODE_ENV: 'production',
        PORT: 3005,
        ...metaEnv
      },
      error_file: 'dashboard/meta-server/logs/pm2/err.log',
      out_file: 'dashboard/meta-server/logs/pm2/out.log',
      log_file: 'dashboard/meta-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        PORT: 3005
      }
    },
    {
      name: "gorgias-server",
      script: "./dashboard/gorgias-server/server.js",
      env: {
        NODE_ENV: "development",
        PORT: 3006
      },
      env_production: {
        NODE_ENV: "production",
        PORT: 3006
      },
      error_file: "dashboard/logs/gorgias-server-error.log",
      out_file: "dashboard/logs/gorgias-server-out.log",
      log_file: "dashboard/logs/gorgias-server-combined.log",
      time: true
    },
    {
      ...commonSettings,
      name: 'google-server',
      script: path.resolve(__dirname, 'dashboard/google-server/server.js'),
      watch: false,
      env: {
        NODE_ENV: 'production',
        GOOGLE_ANALYTICS_PORT: 3007,
        ...googleAnalyticsEnv
      },
      error_file: path.resolve(__dirname, 'dashboard/google-server/logs/pm2/err.log'),
      out_file: path.resolve(__dirname, 'dashboard/google-server/logs/pm2/out.log'),
      log_file: path.resolve(__dirname, 'dashboard/google-server/logs/pm2/combined.log'),
      env_production: {
        NODE_ENV: 'production',
        GOOGLE_ANALYTICS_PORT: 3007
      }
    },
    {
      ...commonSettings,
      name: 'typeform-server',
      script: './dashboard/typeform-server/server.js',
      env: {
        NODE_ENV: 'production',
        TYPEFORM_PORT: 3008,
        ...typeformEnv
      },
      error_file: 'dashboard/typeform-server/logs/pm2/err.log',
      out_file: 'dashboard/typeform-server/logs/pm2/out.log',
      log_file: 'dashboard/typeform-server/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        TYPEFORM_PORT: 3008
      }
    },
    {
      ...commonSettings,
      name: 'inventory-server',
      script: './inventory/src/server.js',
      env: {
        NODE_ENV: 'production',
        PORT: 3010,
        ...inventoryEnv
      },
      error_file: 'inventory/logs/pm2/err.log',
      out_file: 'inventory/logs/pm2/out.log',
      log_file: 'inventory/logs/pm2/combined.log',
      env_production: {
        NODE_ENV: 'production',
        PORT: 3010,
        ...inventoryEnv
      }
    },
    {
      ...commonSettings,
      name: 'new-auth-server',
      script: './inventory-server/auth/server.js',
      env: {
        NODE_ENV: 'production',
        AUTH_PORT: 3011,
        ...inventoryEnv,
        JWT_SECRET: process.env.JWT_SECRET
      },
      error_file: 'inventory-server/auth/logs/pm2/err.log',
      out_file: 'inventory-server/auth/logs/pm2/out.log',
      log_file: 'inventory-server/auth/logs/pm2/combined.log'
    }
  ]
};
