/**
 * crashMonitor.js
 * Place in D:\panel\ (same directory as server.js).
 * Call require('./crashMonitor').init() once from server.js.
 */
const fs   = require('fs');
const path = require('path');

const CRASH_LOG  = path.join(__dirname, 'data', 'crash.log');
const SMTP_CFG   = path.join(__dirname, 'data', 'smtp.json');
const SETTINGS   = path.join(__dirname, 'data', 'settings.json');

// ── Read settings directly from JSON (no require of routes) ──
function loadSettings() {
  const defaults = { crashMonitor: true, crashEmailEnabled: false, crashEmailTo: '', crashEmailSubject: 'ServerPanel — System Crash Detected' };
  try {
    if (!fs.existsSync(SETTINGS)) return defaults;
    return { ...defaults, ...JSON.parse(fs.readFileSync(SETTINGS, 'utf8')) };
  } catch { return defaults; }
}

// ── Write one JSON line to crash.log ──────────────────────
function writeCrashEntry(type, err) {
  const entry = {
    time:    new Date().toISOString(),
    type,
    message: err && err.message ? err.message : String(err),
    stack:   err && err.stack   ? err.stack   : null
  };
  try {
    fs.mkdirSync(path.dirname(CRASH_LOG), { recursive: true });
    fs.appendFileSync(CRASH_LOG, JSON.stringify(entry) + '\n');
  } catch (e) {
    console.error('[crashMonitor] Failed to write crash.log:', e.message);
  }
  return entry;
}

// ── Send crash email via saved SMTP config ─────────────────
async function sendCrashEmail(entry, settings) {
  if (!settings.crashEmailEnabled || !settings.crashEmailTo) return;
  try {
    if (!fs.existsSync(SMTP_CFG)) return;
    const smtp = JSON.parse(fs.readFileSync(SMTP_CFG, 'utf8'));
    if (!smtp.host) return;

    const nm        = require('nodemailer');
    const transport = nm.createTransport({
      host:   smtp.host,
      port:   smtp.port  || 587,
      secure: smtp.secure || false,
      auth:   smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined
    });

    const text = [
      'ServerPanel detected a crash on your server.',
      '',
      'Time:    ' + entry.time,
      'Type:    ' + entry.type,
      'Message: ' + entry.message,
      '',
      entry.stack ? 'Stack trace:\n' + entry.stack : '',
      '',
      'Review the Crash Logs section in ServerPanel for more details.'
    ].join('\n');

    await transport.sendMail({
      from:    smtp.from || smtp.user,
      to:      settings.crashEmailTo,
      subject: settings.crashEmailSubject || 'ServerPanel — System Crash Detected',
      text
    });
    console.log('[crashMonitor] Crash email sent to', settings.crashEmailTo);
  } catch (e) {
    console.error('[crashMonitor] Failed to send crash email:', e.message);
  }
}

// ── Attach process-level handlers ─────────────────────────
function init() {
  process.on('uncaughtException', (err) => {
    console.error('[crashMonitor] Uncaught exception:', err);
    const settings = loadSettings();
    if (!settings.crashMonitor) return;
    const entry = writeCrashEntry('uncaughtException', err);
    sendCrashEmail(entry, settings).catch(() => {});
    // Don't exit — keep the server running for non-fatal errors
  });

  process.on('unhandledRejection', (reason) => {
    console.error('[crashMonitor] Unhandled rejection:', reason);
    const settings = loadSettings();
    if (!settings.crashMonitor) return;
    const e = reason instanceof Error ? reason : new Error(String(reason));
    const entry = writeCrashEntry('unhandledRejection', e);
    sendCrashEmail(entry, settings).catch(() => {});
  });

  console.log('[crashMonitor] Initialized');
}

module.exports = { init, writeCrashEntry };