/* eslint-disable */
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
// const { Pool } = require('pg'); // Database sekarang di-handle oleh Next.js API Routes

const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
// Deteksi port dari env untuk PM2 Cluster
const port = process.env.PORT || 4003;

const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const httpServer = createServer((req, res) => {
    try {
      const parsedUrl = parse(req.url, true);
      handle(req, res, parsedUrl);
    } catch (err) {
      console.error('Error occurred handling', req.url, err);
      res.statusCode = 500;
      res.end('internal server error');
    }
  });

  // FASE 2: SOVEREIGN PURGE
  // ==============================================================================
  // Socket.io, Yjs, dan semua pustaka WebSockets Node.js telah DIBUMIHANGUSKAN.
  // P2P Chat Routing digantikan oleh XCU WebTransport Datagrams (Rust) di Port 8443.
  // Guest Knocking & Otentikasi digantikan oleh Server-Sent Events (SSE) via API.
  // ==============================================================================

  httpServer.once('error', (err) => {
    console.error(err);
    process.exit(1);
  });

  httpServer.listen(port, () => {
    console.log(`> XCU Ultra Chat (NodeJS Layer) Ready on http://${hostname}:${port}`);
    console.log(`> Murni melayani Next.js. WebSockets / Socket.io telah dinonaktifkan (Pindah ke WebTransport).`);
    // PM2 Cluster Ready Signal (KRITIS-7 FIX)
    if (process.send) process.send('ready');
  });
});
