#!/usr/bin/env node

/**
 * Production server for Next.js on cPanel
 * This file starts the Next.js application in production mode
 */

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

const port = process.env.PORT || 3000
const hostname = '0.0.0.0' // Listen on all network interfaces
const dev = false // Always production

console.log('🚀 Starting Next.js production server...')
console.log('📍 Port:', port)
console.log('🌐 Hostname:', hostname)
console.log('🏠 Domain: landing.trendingnow.ge')

// Create Next.js app
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 handling request:', err)
      res.statusCode = 500
      res.end('Internal Server Error')
    }
  }).listen(port, hostname, (err) => {
    if (err) {
      console.error('❌ Failed to start server:', err)
      process.exit(1)
    }
    console.log(`✅ Server running on http://${hostname}:${port}`)
    console.log(`✅ Ready on https://landing.trendingnow.ge`)
  })
})

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('🛑 SIGTERM received, shutting down gracefully...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('🛑 SIGINT received, shutting down gracefully...')
  process.exit(0)
})

process.on('uncaughtException', (err) => {
  console.error('❌ Uncaught exception:', err)
  process.exit(1)
})

process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ Unhandled rejection at:', promise, 'reason:', reason)
  process.exit(1)
})

