// server.js
const express = require("express");
const http = require("http");
const next = require("next");
const { Server } = require("socket.io");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const expressApp = express();
  const server = http.createServer(expressApp);
  const io = new Server(server);

  // WebSocket-Logik
  io.on("connection", socket => {
    console.log("✅ Client verbunden via socket.io");

    socket.on("message", data => {
      console.log("💬 Nachricht vom Client:", data);
    });

    socket.emit("message", { message: "Hallo vom socket.io Server" });
  });

  // Next.js Routen
  expressApp.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, () => {
    console.log(`🚀 Server mit socket.io läuft auf http://localhost:${port}`);
  });
});
