'use strict'; /** * Process entry for the standalone automail server. * * Division of labour (same split genEngine used): * server.js → env + Mongo connection + HTTP server + dashboard (THIS FILE) * index.js → the automail module: mounts routes, seeds scenarios, * starts the poller. Owns NO connection by design. * * So all we do here is: connect Mongo, build the app, then hand it to * automail.register() — which must run AFTER the connection is live. */ require('dotenv').config(); const path = require('path'); const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); const automail = require('./index'); // <-- your existing module (register/startPoller/stopPoller) const PORT = process.env.PORT || 1000; const MONGO_URI = process.env.MONGO_URI; async function start() { if (!MONGO_URI) { console.error('[server] MONGO_URI missing in .env — cannot start.'); process.exit(1); } // 1. Connection first — the module assumes it already exists. await mongoose.connect(MONGO_URI); console.log('[server] Mongo connected'); // 2. Build the host app + middleware the module relies on. const app = express(); app.use(cors()); // client's own app calls cross-origin app.use(express.json()); // routes read req.body (approve/edit/settings) app.use(express.static(path.join(__dirname, 'public'))); // dashboard at / app.get('/health', (_req, res) => res.json({ ok: true, uptime: process.uptime() })); // 3. Hand the app to automail — mounts /automail, seeds scenarios, starts poller. await automail.register(app); // basePath defaults to /automail; poller starts unless startPoller:false // 4. Now that all routes are mounted, listen. app.listen(PORT, () => { console.log(`[server] server http://localhost:${PORT}`); console.log(`[server] dashboard http://localhost:${PORT}/`); console.log(`[server] api http://localhost:${PORT}/automail`); }); } // Clean poller shutdown on Ctrl+C. process.on('SIGINT', () => { try { automail.stopPoller && automail.stopPoller(); } catch {} mongoose.connection.close().finally(() => process.exit(0)); }); start().catch((err) => { console.error('[server] failed to start —', err); process.exit(1); });