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

// 1. Configuración de Logs de Error
const logFile = path.join(__dirname, 'passenger_error.log');

function logError(title, err) {
  const date = new Date().toISOString();
  const errMsg = err && err.stack ? err.stack : err;
  const message = `[${date}] === ${title} ===\n${errMsg}\n\n`;
  try {
    fs.appendFileSync(logFile, message);
  } catch (e) {
    console.error(message);
  }
}

// Capturar excepciones y promesas no controladas
process.on('uncaughtException', (err) => {
  logError('UNCAUGHT EXCEPTION', err);
});
process.on('unhandledRejection', (reason, promise) => {
  logError('UNHANDLED REJECTION', reason);
});

// Registrar variables de entorno (ocultando valores sensibles) para depurar
try {
  const debugEnv = {};
  for (const key of Object.keys(process.env)) {
    const val = process.env[key];
    if (
      key.includes('KEY') ||
      key.includes('SECRET') ||
      key.includes('PASSWORD') ||
      key.includes('TOKEN') ||
      key.includes('ANON')
    ) {
      debugEnv[key] = val ? `${val.substring(0, 8)}... (longitud: ${val.length})` : 'vacía';
    } else {
      debugEnv[key] = val;
    }
  }
  logError('ENVIRONMENT DETAILS', JSON.stringify(debugEnv, null, 2));
} catch (e) {
  logError('ENV LOGGING ERROR', e);
}

// 2. Interceptar y parchar http.Server.prototype.listen
// Esto evita que Node.js intente usar el segundo argumento (hostname) cuando Passenger pasa un Socket Unix (String)
const originalListen = http.Server.prototype.listen;
http.Server.prototype.listen = function (port, hostname, backlog, callback) {
  if (typeof port === 'string' && isNaN(parseInt(port, 10))) {
    let cb = callback;
    if (typeof hostname === 'function') cb = hostname;
    else if (typeof backlog === 'function') cb = backlog;
    
    logError('LISTEN SOCKET DETECTED', `Escuchando en Socket Unix: ${port}`);
    return originalListen.call(this, port, cb);
  }
  return originalListen.apply(this, arguments);
};

// 3. Cargar el servidor Next.js standalone original (renombrado a next-standalone-server.js)
try {
  logError('STARTUP', 'Iniciando wrapper del servidor Next.js standalone...');
  require('./next-standalone-server.js');
} catch (err) {
  logError('REQUIRE ERROR (next-standalone-server.js)', err);
  process.exit(1);
}
