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

// Point to the standalone server
// cPanel runs this file from the root, but the standalone build is deep inside .next
const standaloneServerPath = path.join(__dirname, '.next', 'standalone', 'server.js');

// If standalone server exists, verify it implies we should use it. 
// However, the standalone server.js isn't just a require-able module often, it STARTS the server.
// A better approach for cPanel + Standalone is to just use the standard custom server 
// that mimics 'next start' but uses the standalone build's node_modules if needed.

// SIMPLIFIED APPROACH:
// We will just require the standalone server which boots itself.
// But we need to ensure CWD is correct.

process.env.NODE_ENV = 'production'
process.chdir(__dirname)

// Check if we are running from the root or inside standalone
// This script is intended to be at project root.
try {
  require('./.next/standalone/server.js')
} catch (e) {
  console.error("Could not find standalone server at ./.next/standalone/server.js");
  console.error("Falling back to standard next start logic (will fail if node_modules are missing)");
    
  const dev = process.env.NODE_ENV !== 'production'
  const hostname = 'localhost'
  const port = process.env.PORT || 3000
  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('Error occurred handling', req.url, err)
        res.statusCode = 500
        res.end('internal server error')
      }
    })
      .once('error', (err) => {
        console.error(err)
        process.exit(1)
      })
      .listen(port, () => {
        console.log(`> Ready on http://${hostname}:${port}`)
      })
  })
}
