import "dotenv/config";
import express from "express";
import http from "http";
import { Server } from "socket.io";
import { initSocketEvents } from "./events";
import { env } from "@/env";

declare global {
  var io: Server | undefined;
}

const createSocketServer = () => {
  const app = express();
  const server = http.createServer(app);

  const PORT = env.SOCKET_IO_PORT || 4000;
  const origin = env.SOCKET_IO_CORS_ORIGIN || "http://localhost:" + PORT;

  if (!global.io) {
    global.io = new Server(server, {
      cors: {
        origin,
        methods: ["GET", "POST"],
      },
    });

    initSocketEvents(global.io);

    server.listen(PORT, () => {
      console.log(`Socket.IO server running on port ${PORT}`);
    });
  }

  return global.io;
};

export const ioServer = createSocketServer();
