/**
 * server.js — Custom Next.js server untuk cPanel (Phusion Passenger)
 *
 * Digunakan saat deploy di shared hosting / VPS dengan Node.js App.
 * Vercel tidak butuh file ini (Vercel punya runtime sendiri).
 *
 * Cara pakai:
 *   1. npm run build   (jalankan di lokal atau via SSH)
 *   2. Upload semua file ke cPanel (kecuali node_modules & .next)
 *   3. Di cPanel Node.js App → Application startup file: server.js
 *   4. Run NPM Install di cPanel
 *   5. Start / Restart application
 */

'use strict';

const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev  = process.env.NODE_ENV !== 'production';
const port = parseInt(process.env.PORT || '3000', 10);
const hostname = process.env.HOSTNAME || 'localhost';

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

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      const parsedUrl = parse(req.url, true);
      await handle(req, res, parsedUrl);
    } catch (err) {
      console.error('[server] Error handling request:', err);
      res.statusCode = 500;
      res.end('Internal Server Error');
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> PromptMotion AI ready on http://${hostname}:${port}`);
    console.log(`> Environment: ${process.env.NODE_ENV || 'development'}`);
  });
});
