import http from "node:http";
import express from "express";
import cors from "cors";
import { Server } from "@colyseus/core";
import { WebSocketTransport } from "@colyseus/ws-transport";
import { monitor } from "@colyseus/monitor";
import { LobbyRoom } from "./rooms/LobbyRoom.ts";

const port = Number(process.env.PORT) || 2567;

const app = express();
const server = http.createServer(app);
const transport = new WebSocketTransport({ server });

const gameServer = new Server({ transport });

// CORS — allow all al-arcade.com origins
app.use(cors({
  origin: (origin, callback) => {
    if (!origin) return callback(null, true);
    if (
      origin.endsWith(".al-arcade.com") ||
      origin === "https://al-arcade.com" ||
      origin === "http://al-arcade.com" ||
      origin === "http://localhost:3000" ||
      origin === "http://localhost:8080"
    ) {
      return callback(null, true);
    }
    callback(null, true); // allow all for now during dev
  },
  credentials: true,
}));

app.use(express.json());

app.get("/health", (req, res) => {
  res.json({
    status: "ok",
    uptime: process.uptime(),
    rooms: gameServer.matchMaker ? "active" : "initializing",
  });
});

app.use("/monitor", monitor());

// Define the lobby room
gameServer.define("lobby", LobbyRoom);

gameServer.listen(port).then(() => {
  console.log(`[AL-Arcade] Colyseus server listening on port ${port}`);
  console.log(`[AL-Arcade] Health: http://localhost:${port}/health`);
  console.log(`[AL-Arcade] Monitor: http://localhost:${port}/monitor`);
});
