import { Server } from "socket.io";
import axios from "axios";
import { handleConnectionEvents } from "./events/connection.js";
import { addUser, removeUser } from "./state/connection.js";
import gameEvents from "./events/game.js";

export const server = {
  io: null,
};

const API_URL = "http://localhost:8000/api/v1";

export const serverStart = (port) => {
  server.io = new Server(port, {
    cors: {
      origin: "*",
    },
  });

  server.io.use(async (socket, next) => {
    const token = socket.handshake.auth.token;

    if (!token) {
      return next(new Error("Authentication error: No token provided"));
    }

    try {
      const response = await axios.get(`${API_URL}/users/me`, {
        headers: { Authorization: token },
      });

      const user = response.data.data || response.data;

      if (!user || !user.id) {
        return next(new Error("Authentication error: User data not found"));
      }

      addUser(socket.id, user);

      next();
    } catch (error) {
      if (error.response) {
        console.error(
          "❌ Erro Laravel:",
          error.response.status,
          error.response.data
        );
      } else {
        console.error("❌ Erro Rede:", error.message);
      }
      next(new Error("Authentication error: Invalid token"));
    }
  });

  server.io.on("connection", (socket) => {
    console.log("New connection:", socket.id);

    gameEvents(server.io, socket);

    handleConnectionEvents(server.io, socket);

    socket.on("disconnect", () => {
      removeUser(socket.id);
      console.log("Disconnected:", socket.id);
    });
  });
};
