// PM2 process config
// Start:   pm2 start ecosystem.config.cjs
// Save:    pm2 save
// Startup: pm2 startup systemd

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

// Parse .env.production manually so PM2 always picks up the latest values
// regardless of PM2 version's env_file support.
function loadEnv(envPath) {
  try {
    const content = fs.readFileSync(envPath, "utf8");
    const env = {};
    for (const line of content.split("\n")) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      const eqIdx = trimmed.indexOf("=");
      if (eqIdx === -1) continue;
      const key = trimmed.slice(0, eqIdx).trim();
      const val = trimmed.slice(eqIdx + 1).trim();
      env[key] = val;
    }
    return env;
  } catch {
    return {};
  }
}

const ENV_FILE = path.resolve(__dirname, ".env.production");
const env = loadEnv(ENV_FILE);

module.exports = {
  apps: [
    {
      name: "homelegance-chat",
      script: "./dist/index.js",
      cwd: "/redant/web/homelegance-chatbot",
      env,                          // inject all vars from .env.production
      instances: 1,
      autorestart: true,
      max_memory_restart: "512M",
      error_file: "/var/log/pm2/homelegance-chat-error.log",
      out_file: "/var/log/pm2/homelegance-chat-out.log",
      log_date_format: "YYYY-MM-DD HH:mm:ss",
    },
  ],
};
