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

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

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

// Fonction pour obtenir l'IP locale
function getLocalIp() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      const { address, family, internal } = iface;
      if (family === 'IPv4' && !internal) {
        return address;
      }
    }
  }
  return 'localhost';
}

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, hostname, () => {
      const localIp = getLocalIp();
      console.log(`\n✨ Serveur Next.js démarré !\n`);
      console.log(`  🏠 Local:   http://localhost:${port}`);
      console.log(`  📱 Network: http://${localIp}:${port}`);
      console.log(`\n  Pour accéder depuis mobile: http://${localIp}:${port}\n`);
    });
});
